gpt4 book ai didi

java - 使用 java.lang.String.matches() 查找匹配项

转载 作者:行者123 更新时间:2023-11-29 03:32:20 26 4
gpt4 key购买 nike

我有一个包含换行符的字符串 say...

str = "Hello\n"+"Batman,\n"+ "Joker\n"+ "here\n"

我想知道如何使用 java.lang.String.matches 在字符串 str 中找到特定单词 say .. Joker 的存在()

我发现 str.matches(".*Joker.*") 返回 false 并返回 true 如果我删除新行人物。那么用作 str.matches() 参数的正则表达式是什么?

一种方法是... str.replaceAll("\\n","").matches(.*Joker.*);

最佳答案

问题是 .* 中的点默认不匹配换行符。如果你想匹配换行符,你的正则表达式必须有标志 Pattern.DOTALL .

如果您想将其嵌入到 .matches() 中使用的正则表达式中,则正则表达式为:

"(?s).*Joker.*"

但是,请注意,这也将匹配 Jokers。正则表达式没有单词的概念。因此,您的正则表达式真的需要是:

"(?s).*\\bJoker\\b.*"

然而,正则表达式不需要匹配所有它的输入文本(这是 .matches() 所做的,违反直觉),只匹配需要的。因此,这个解决方案更好,并且不需要Pattern.DOTALL:

Pattern p = Pattern.compile("\\bJoker\\b"); // \b is the word anchor

p.matcher(str).find(); // returns true

关于java - 使用 java.lang.String.matches() 查找匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17587718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com