检查字符串中是否存在模式

Fai*_*sal 4 java regex

我尝试搜索,但找不到任何对我有意义的东西!我是正则表达式的菜鸟 :)

尝试查看特定单词“some_text”是否存在于另一个字符串中。

String s = "This is a test() function"
String s2 = "This is a test    () function"
Run Code Online (Sandbox Code Playgroud)

假设有上述两个字符串,我可以在RegEx Tool 中使用以下模式进行搜索

[^\w]test[ ]*[(]
Run Code Online (Sandbox Code Playgroud)

但无法在 Java 中使用正匹配

System.out.println(s.matches("[^\\w]test[ ]*[(]");
Run Code Online (Sandbox Code Playgroud)

我曾尝试使用双 \ 甚至四个 \\ 作为转义字符,但没有任何效果。

要求是看到单词以空格开头或者是一行的第一个单词并且在该特定单词之后有一个左括号“(”,这样所有这些“test()、test()或test()”应该得到一场积极的比赛。

使用 Java 1.8

干杯,费萨尔。

vs9*_*s97 5

您缺少的一点是 Java为您在 Regex的开头和结尾matches()放置了^a $。所以你的表达实际上被视为:

^[^\w]test[ ]*[(]$
Run Code Online (Sandbox Code Playgroud)

这永远不会与您的输入相匹配。

从您的需求描述来看,我建议将您的正则表达式改写成这样(假设您的意思是“特定词” test):

(?:.*)(?<=\s)(test(?:\s+)?\()(?:.*)
Run Code Online (Sandbox Code Playgroud)

在此处查看工作中的正则表达式。

解释:

^                 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()
Run Code Online (Sandbox Code Playgroud)

代码示例:

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
    }
}
Run Code Online (Sandbox Code Playgroud)