Question

I have below content in file

/** 
 some text
 text1 
 text2
 some text
**/

I want to check if "text1" or "text2" is contained in between /** **/ as mentioned in above example.

I tried below code

  Pattern p = Pattern.compile("//*/*.*?text1.*?/*/*/");
  Matcher m = p.matcher(fileAsString);
  while (m.find()) {
    System.out.println("match found");
  }

but it has two shortcomings . These are :-

1) It checks for text1 in between /** text1 **/ but does not work when text1 is in next line

2)I am not sure how to check any of the two strings i.e "text1" or "text2" in this regex?

Was it helpful?

Solution

You can use:

Pattern p = Pattern.compile("/\\*\\*.*?(?:text1|text2).*?\\*\\*/", Pattern.DOTALL);
  1. Pattern.DOTALL is required to make sure to match text spanning multiple lines
  2. * needs to be escaped using \\*
  3. (?:text1|text2) is a non capturing alternation, needed to match text1 or text2.

OTHER TIPS

The following pattern will ensure that you are always inside the comment part when text1 or text2 is found. To do that I repeat a group that can not match the comment end **/: (?>[^*]|\\*(?!\\*/))*

Pattern p = Pattern.compile("\\Q/**\\E"
                          + "(?>[^*]|\\*(?!\\*/))*?"
                          + "(?:text1|text2)"
                          + "(?>[^*]|\\*(?!\\*/))*"
                          + "\\Q**/\\E");

do you have to use a regex? would String.indexOf be a possible way to tell if the text is contained? You can substring the inner string between the /* */ tags and then do an indexOf

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top