Regex - How to make sure only 1 instance of character occuring between two characters or from start to certain character

Mert Serimer :

I want to make sure only 1 instance of comoa occurs before parenthesis. Parenthesis is a must. I need to make sure all string matches the pattern. Regex matcher must not substring.

Examples;

 Mert,sert , abc() = not valid
 Mert, asd( = valid
 Mert , asd,( = not valid
 Mert , asd = not valid

I tried this one and also can you explain why it did not work? Thanks

.+,[^,]+\(.+
Wiktor Stribiżew :

You may use

^[^,(]*,[^,(]*\(.*

See the regex demo

In Java, use

Boolean result = s.matches("[^,(]*,[^,(]*\\(.*");

Or, if there can be line breaks, s.matches("(?s)[^,(]*,[^,(]*\\(.*").

Details

  • ^ - start of string (it is not necessary in String#matches)
  • [^,(]* - 0 or more chars other than a comma and open parenthesis
  • , - a comma
  • [^,(]* - 0 or more chars other than a comma and open parenthesis
  • \( - an open parenthesis
  • .* - the rest of the line / string (with (?s)).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=147476&siteId=1