我尝试搜索,但找不到任何对我有意义的东西!我是正则表达式的菜鸟 :)
尝试查看另一个字符串中是否存在特定单词“some_text”。
String s = "This is a test() function"
String s2 = "This is a test () function"
[^\w]test[ ]*[(]
System.out.println(s.matches("[^\\w]test[ ]*[(]");
最佳答案
您缺少的一点是 Java matches()
为您在 Regex 的开头和末尾放置了一个 ^
$
。所以你的表达实际上被视为:
^[^\w]test[ ]*[(]$
test
):(?:.*)(?<=\s)(test(?:\s+)?\()(?:.*)
^ Start of line - added by matches()
(?:.*) Non-capturing group - match anything before the word, but dont capture into a group
(?<=\s) Positive lookbehind - match if word preceded by space, but dont match the space
( Capturing group $1
test(?:\s+)? Match word test and any following spaces, if they exist
\( Match opening bracket
)
(?:.*) Non-capturing group - match rest of string, but dont capture in group
$ End of line - added by matches()
public class Main {
public static void main(String[] args) {
String s = "This is a test() function";
String s2 = "This is a test () function";
System.out.println(s.matches("(?:.*)((?<=\\s))(test(?:\\s+)?\\()(?:.*)"));
//true
}
}
https://stackoverflow.com/questions/60464842/