0

I have a string which is invalid if it has

  _ at start ||
  _ at end ||
  more than one consecutive _ in the middle 

but it is valid if more than one non consecutive _ found in a string

examples are

"'test_test_test" - valid 
"test_" - invalid
"_test" - invalid
"test_____test" - invalid

I am trying different pattern to match all this condition into one but doesn't seem to work for e.g.("^[__]+") or ("^[_]+") or ("^[_]$+")

If you could help me with regex and some explanation, I would really appreciate!

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
user1298426
  • 3,467
  • 15
  • 50
  • 96

1 Answers1

0

You can use below code:

Pattern p = Pattern.compile("^(_\\w*)|(\\w*_{2,}+\\w*)|(\\w*_$)");
Matcher m = p.matcher("te_st_");
System.out.println("Is string invalid: "+ m.matches());

See the result: https://ideone.com/hwMzL1

For more details: Pattern

Sumit Singh
  • 15,743
  • 6
  • 59
  • 89