在 Java 中如何在 String.has()方法中使用 regex

我想检查一个 String 是否按照这个顺序包含单词“ store”、“ store”和“ product”,不管它们之间有什么。

我尝试使用 someString.contains(stores%store%product);.contains("stores%store%product");

我是否需要显式声明一个正则表达式并将其传递给方法,或者我根本不能传递正则表达式?

354848 次浏览

包含

String.contains使用 String,句号。正则表达式不起作用。它将检查指定的确切 String 是否出现在当前 String 中。

注意,String.contains不检查单词边界; 它只检查子字符串。

正则表达式解决方案

正则表达式比 String.contains更强大,因为您可以在关键字上强制执行单词边界(以及其他事情)。这意味着您可以将关键字搜索为 文字,而不仅仅是 子串

使用 String.matches的正则表达式如下:

"(?s).*\\bstores\\b.*\\bstore\\b.*\\bproduct\\b.*"

RAW regex (删除字符串文字中的转义——这是打印出上面的字符串时得到的结果) :

(?s).*\bstores\b.*\bstore\b.*\bproduct\b.*

\b检查单词边界,这样就不会得到与 restores store products匹配的单词。请注意,stores 3store_product也被拒绝,因为数字和 _被认为是一个词的一部分,但我怀疑这种情况下出现在自然的文本。

因为双方都检查了单词边界,所以上面的正则表达式将搜索确切的单词。换句话说,stores stores product将不匹配上面的正则表达式,因为您正在搜索没有 s的单词 store

.通常匹配任何字符 除了 一些新的行字符(?s)在开始使 .匹配任何字符没有例外(感谢提姆皮茨克指出这一点)。

matcher.find()做你需要的。例如:

Pattern.compile("stores.*store.*product").matcher(someString).find();

您可以简单地使用 String 类的 matches方法。

boolean result = someString.matches("stores.*store.*product.*");

如果希望检查字符串是否包含子字符串或不使用正则表达式,最接近的方法是使用 find ()-

    private static final validPattern =   "\\bstores\\b.*\\bstore\\b.*\\bproduct\\b"
Pattern pattern = Pattern.compile(validPattern);
Matcher matcher = pattern.matcher(inputString);
System.out.print(matcher.find()); // should print true or false.

注意 match ()和 find ()之间的区别,如果整个字符串匹配给定的模式,match ()返回 true。Find ()尝试查找与给定输入字符串中的模式匹配的子字符串。另外,通过使用 find () ,您不必添加额外的匹配,如-(?S).* at the start and.* at the end of your regex pattern.

public static void main(String[] args) {
String test = "something hear - to - find some to or tows";
System.out.println("1.result: " + contains("- to -( \\w+) som", test, null));
System.out.println("2.result: " + contains("- to -( \\w+) som", test, 5));
}
static boolean contains(String pattern, String text, Integer fromIndex){
if(fromIndex != null && fromIndex < text.length())
return Pattern.compile(pattern).matcher(text).find();


return Pattern.compile(pattern).matcher(text).find();
}

1. 结果: 正确

2. 结果: 正确

爪哇11开始,人们可以使用返回 Predicate<String>Pattern#asMatchPredicate

String string = "stores%store%product";
String regex = "stores.*store.*product.*";
Predicate<String> matchesRegex = Pattern.compile(regex).asMatchPredicate();


boolean match = matchesRegex.test(string);                   // true

该方法支持 锁链与其他 String 谓词,只要 Predicate提供 andornegate方法,这就是该方法的主要优点。

String string = "stores$store$product";
String regex = "stores.*store.*product.*";


Predicate<String> matchesRegex = Pattern.compile(regex).asMatchPredicate();
Predicate<String> hasLength = s -> s.length() > 20;


boolean match = hasLength.and(matchesRegex).test(string);    // false