Home > Back-end >  How do I make a regex part optional and finish regex at the same point if that optional part contain
How do I make a regex part optional and finish regex at the same point if that optional part contain

Time:12-16

String s1 = "NetworkElement=Test,testWork=1:[456]";
String s2 = "NetworkElement=Test,testWork=1";
String regex = "(.*):\\[(.*)\\]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s1);  
if(matcher.find()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
}
Matcher matcher2 = pattern.matcher(s2);  
if(matcher2.find()) {
System.out.println(matcher2.group(1));
System.out.println(matcher2.group(2));
}

/*
Expected output:
for s1 : NetworkElement=Test,testWork=1
         456
for s2 : NetworkElement=Test,testWork=1
         0
*/

Problem : This regex is working fine for String s1 but not for s2. for string s2, matcher2.find() return false.

CodePudding user response:

You can use

^(.*?)(?::\[(.*?)])?$
^(.*?)(?::\[([^\]\[]*)])?$

See the regex demo.

In Java:

String regex = "^(.*?)(?::\\[(.*?)])?$";
// Or
String regex = "^(.*?)(?::\\[([^\\]\\[]*)])?$";

I added the ^ and $ anchors since you are using matcher.find(). If you switch to matcher.matches(), you can remove the anchors.

Details:

  • ^ - start of string
  • (.*?) - Group 1: any zero or more chars other than line break chars as few as possible
  • (?::\[(.*?)])? - an optional sequence of :[, then Group 2 capturing any zero or more chars other than line break chars as few as possible and then a ] char (if you use [^\]\[]* it will match zero or more chars other than square brackets)
  • $ - end of string.
  • Related