简体   繁体   中英

How to match an exact match in a string using Java

I am trying to check if a string contains an exact match. For example:
String str = "This is my string that has -policy and -p"

How can I do the following:

if (str.contains("-p")) {  // Exact match to -p not -policy
System.out.println("This is -p not -policy");

}

To differentiate the -p this below solution simply works. If we add /b in the front then the "test-p" kind of word will also be matched.

String source = "This is -p not -policy";
System.out.println("value is " + Pattern.compile(" -p\\b").matcher(source).find());

Try with:

(?<!\w)\-p(?!\w)

DEMO

Which means:

  • (?<!\\w) negative lookbehind for any word character (A-Za-z0-9_) so if it will be preceded by &*%^%^ it will match anyway,
  • \\-p - -p
  • (?!\\w) negative lookahead for any word character (A-Za-z0-9_), as above

Another solution could be also:

(?<=\s)\-p(?=\s)

then there must be space char (' ') before and anfter -p

Implementation in Java with Pattern and Matcher classes:

public class Test {
    public static void main(String[] args) {
        String sample = "This is my string that has -policy and -p";
        Pattern pattern = Pattern.compile("(?<!\\w)\\-p(?!\\w)");
        Matcher matcher = pattern.matcher(sample);
        matcher.find();
        System.out.println(sample.substring(matcher.start(), matcher.end()));
        System.out.println(matcher.group(0));
    }
}

You can try this way.

String str = "This is my string that has -policy and -p";
for(String i:str.split(" ")){
   if(i.equals("-p")){ // now you are checking the exact match
     System.out.println("This is -p not -policy");
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM