【问题标题】:REGEX matching with any character(s) between 2 strings [duplicate]正则表达式匹配两个字符串之间的任何字符[重复]
【发布时间】:2017-08-31 21:26:25
【问题描述】:

我用一个正则表达式测试器试过这个,它可以工作。但是为什么我不能让它为 JAVA 工作。 我希望搜索neither..........nor

我想计算一个字符串中有多少neithersomethingnor"Neither u or me are human"

我试过了:

occurrence += sentence.split( "(?i)\\Wneither.+nor\\W" ).length - 1;

但它不起作用,因为输出 System.out.print(occurrence) 结果是 0

我认为\\W 代表非单词字符,而.+ 表示任何字符。

如何获得1occurrence 结果?

【问题讨论】:

  • this is not working 不是问题描述,对于您未解释的问题的任何解决方案 都不是问题。您对该正则表达式有什么具体问题,您希望我们为您解答什么具体问题
  • “neither.+nor”在“Neither u or me are human”中出现的次数为零。至少出现 1 次语法错误:-)
  • 如果您正在寻找 neither ABC nor(其中 ABC 是任何单词),那么您的 "Neither u or me are human" 给出的结果为零是正确的。如果字符串是"Neither u nor me are human",那么您可以预期结果为 1,不是吗?你的问题真的只是“如何计算句子中有多少neither和多少nor

标签: java regex


【解决方案1】:

你可以用这个来计算出现次数:

Pattern pattern = Pattern.compile("(neither|nor)", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("Neither u or me are human");

int count = 0;
while (matcher.find())
    count++;

System.out.println(count);

【讨论】:

  • 提问者已更新(更改规则)预期结果。他们特别想要(neither + * + nor),其中*既不是也不是这两个词之间的任何东西,或者至少在我看来
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
  • 1970-01-01
  • 2022-07-06
  • 1970-01-01
  • 2011-08-31
  • 1970-01-01
相关资源
最近更新 更多