如何使用Java匹配字符串中的完全匹配

时间:2015-08-14 06:57:15

标签: java regex string

我正在尝试检查字符串是否包含完全匹配。 例如:
String str =“这是我的字符串,其中包含-policy和-p”

如何执行以下操作:

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

}

3 个答案:

答案 0 :(得分:2)

为了区分-p,下面的解决方案很简单。如果我们在前面添加/ b,那么“test-p”类型的单词也将匹配。

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

答案 1 :(得分:1)

尝试:

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

DEMO

这意味着:

    对于任何单词字符(A-Za-z0-9_),
  • (?<!\w)负向后看 如果它前面会有&amp; *%^%^它将会匹配,
  • \-p - -p
  • 任何单词字符(A-Za-z0-9_)的
  • (?!\w)否定前瞻,如 上述

另一种解决方案也可能是:

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

然后在-p

之前必须有空格char('')

使用PatternMatcher类在Java中实现:

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));
    }
}

答案 2 :(得分:0)

你可以这样试试。

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");
   }
}
相关问题