gpt4 book ai didi

java - 使用正则表达式匹配单词 '90%'

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:58:26 25 4
gpt4 key购买 nike

我希望单词“90%”与我的字符串“我拥有这家公司的 90% 股份”相匹配。

如何编写相同的正则表达式?

我试过这样的:

Pattern p = Pattern.compile("\\b90\\%\\b", Pattern.CASE_INSENSITIVE
| Pattern.MULTILINE);
Matcher m = p.matcher("I have 90% shares of this company");
while (m.find()){
System.out.println(m.group());
}

但没有运气。

任何人都可以对此有所了解吗?

非常感谢,文件馆

最佳答案

"%"中间没有\b字界;这就是您的模式失败的原因。

改为使用此模式:

"\\b90%"

另见

There are three different positions that qualify as word boundaries:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

因此在两个字符之间,\b 仅存在于 \W\w 之间(以任意顺序)。

'%'''都是\W,所以这就是为什么两者之间没有\b的原因它们在 "% " 中。

关于java - 使用正则表达式匹配单词 '90%',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2780759/

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