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

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

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

String s = "This is a test() function"
String s2 = "This is a test    () function"

假设有上述两个字符串,我可以在 RegEx Tool 使用以下模式进行搜索
[^\w]test[ ]*[(]

但无法在 Java 中使用正匹配
System.out.println(s.matches("[^\\w]test[ ]*[(]");

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

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

使用 Java 1.8

干杯,
费萨尔。

最佳答案

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

^[^\w]test[ ]*[(]$

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

从您的需求描述来看,我建议将您的正则表达式改写成这样(假设“特定词”是指 test ):
(?:.*)(?<=\s)(test(?:\s+)?\()(?:.*)

See the regex at work here.

解释:
^                 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/

相关文章:

java - Java 中的静态方法调用是如何工作的?

r - 如何创建一个因子但保留基础值,而不仅仅是整数代码?

java - 在NIFI中创建自定义 Controller 服务时无法生成扩展的文档

java - 如何将充满 if 语句的 for 循环更改为更优雅/高效的代码?

prolog - Prolog数据库的Web访问

object-detection - 使用 >450K 个实例训练 Dlib 对象检测

electron - 如何将在 Electron 上开发的桌面应用程序打包成.exe?

intellij-idea - IdeaVim:如何在不使用箭头键的情况下循环浏览列表项?

java - 这个While 循环可以简化吗?

c - 我无法理解打印第一个八个数组元素的数组的输出