英文:
How to find if a word immediately followed by a non-letter character exists in a String
问题
我相信这个问题的最有效解决方案是使用正则表达式,但我对语法不确定。在查看句子时,如何确定在字符串中是否存在一个单词后面跟着一个非字母字符(除了 a、b、c、d、e... 以外的任何字符)。以下是示例:
String word = "eat";
String sentence = "我喜欢吃饭!"
这满足条件,因为叹号不是字母。
String sentence = "我喜欢打球!"
这不满足条件,因为 "打球" 不是 "吃饭"。这也是 contains() 方法失效的情况。
String sentence = "我喜欢吃东西"
这不满足条件,因为 "吃" 后面跟着一个字母。
英文:
I believe the most efficient solution to this issue is to use Regex but I'm uncertain of the syntax. When looking through a sentence, how do you identify if a word followed by a non-letter character (anything other than a,b,c,d,e...) is present in a string. Example below:
String word = "eat"
String sentence = "I like to eat!"
This satisfies the condition because the exclamation point is not a letter
String sentence = "I like to beat!"
This does not satisfy the condition because beat is not eat. This is also an application where the contains() method fails
String sentence = "I like to eats"
This does not satisfy the condition because eat is followed by a letter
答案1
得分: 3
使用 单词边界 正则表达式 \b
,它匹配字母与非字母之间(或反之)的位置:
str.matches(".*\\b" + word + "\\b.*")
查看 演示示例。
尽管数字也被视为“单词字符”,但这对您应该有效。
我还在开头处使用了单词边界,以便 "I want to beat" 不会匹配。
英文:
Use the word boundary regex \b
, which matches between a letter and a non-letter (or visa versa):
str.matches(".*\\b" + word + "\\b.*")
See live demo.
Although numbers are also considered "word characters", this should work for you.
I've used a word boundary are the start too so "I want to beat" does not match.
答案2
得分: 2
你可以使用:
sentence.matches(".*\\b" + word + "[^a-zA-Z\\s].*");
如果你想让"I like to eat"也匹配,你可以使用:
sentence.matches(".*\\b" + word + "([^a-zA-Z\\s]|$).*");
英文:
You can use:
sentence.matches(".*\\b" + word + "[^a-zA-Z\\s].*");
If you want "I like to eat" to also match, you can use:
sentence.matches(".*\\b" + word + "([^a-zA-Z\\s]|$).*");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论