-2

Can't find why my function that detect if in the targeted text there is a match for a certain regular expression does not work for this example:

regular expression:

"(?s).*<name>.+</name>.*​"

targeted text:

<queryContextResponse>
  <contextResponseList>
    <contextElementResponse>
      <contextElement>
        <entityId type="Room" isPattern="false">
          <id>Room1</id>
        </entityId>
        <contextAttributeList>
          <contextAttribute>
            <name>pressure</name>
            <type>integer</type>
            <contextValue>720</contextValue>
          </contextAttribute>
          <contextAttribute>
            <name>temperature</name>
            <type>float</type>
            <contextValue>23</contextValue>
          </contextAttribute>
        </contextAttributeList>
      </contextElement>
      <statusCode>
        <code>200</code>
        <reasonPhrase>OK</reasonPhrase>
      </statusCode>
    </contextElementResponse>
  </contextResponseList>
</queryContextResponse>

the function

    private boolean isStringContainsReg(String reg, String text){
        try
        {
            Pattern pattern = Pattern.compile(reg);
            Matcher matcher = pattern.matcher(text);
            if (matcher.find()) {   
                return true;
            } 
        }
        catch(PatternSyntaxException e){            
            e.printStackTrace();            
        }
        return false;
    }

However when I test it on this online website, it works: http://java-regex-tester.appspot.com/

sabrina2020
  • 2,102
  • 3
  • 25
  • 54

1 Answers1

0

changing the pattern to (?s).*?<name>.+</name>.*​? solves the issues - I just replaced .* wildcards to the non-greedy .*?. And by the way, there is the method String#matches(String regex) which does pretty much what your function isStringContainsReg does...

Binkan Salaryman
  • 3,008
  • 1
  • 17
  • 29