【问题标题】:How to match immediately previous word pattern in java?如何在java中立即匹配前一个单词模式?
【发布时间】:2014-03-31 11:05:29
【问题描述】:

我有一个这样的字符串:

"value of <abc/def> ends with <def> and value of <abc/def> does not end with <abc> and value of <abc> is <abc>"

我想提取字符串value of &lt;abc/def&gt; does not end with &lt;abc&gt;
我使用了以下模式

String text = "value of <abc/def> ends with <def> and value of <abc/def> does not end with <abc> and value of <abc> is <abc>";
String patternString1 = "(value\\s+of\\s+(<.*>)\\s+ends\\s+with\\s+(<.*>))";
Pattern pattern = Pattern.compile(patternString1);
Matcher matcher = pattern.matcher(text);
while(matcher.find()) {
    System.out.println("found: " + matcher.group(1));
}

结果:-

found: value of <abc/def> ends with <def> and value of <abc/def> does not end with <abc> and value of <abc> is <abc>

【问题讨论】:

  • .* 默认为greedy。您需要通过添加? 使其变得懒惰。至少我认为这是问题所在——我不太明白这个问题。
  • 我真的不知道你的真正意思是什么,但也许修改 * 的贪婪会成功,改为 *?。这将尽可能少地抓取字符。
  • 为什么你的正则表达式试图匹配ends with-part,而你说,你想匹配does not end with-part?这有点令人困惑。

标签: java regex string


【解决方案1】:

正如你的意思是得到value of &lt;abc/def&gt; does not end with &lt;abc&gt; 更正后的模式:

String patternString1 = "(value\\s+of\\s+(<[^>]*>)\\s+does\\s+not\\s+end\\s+with\\s+(<[^>]*>))";

【讨论】:

    【解决方案2】:

    尝试使用下面的代码。

    String text = "value of ends with and value of does not end with and value of is ";
    String arr[] = text.split(" and ");
    System.out.println(arr[1]);
    

    这会将字符串分成三部分。这会对您有所帮助。

    【讨论】:

    • 谢谢...但问题是 之间的所有字符都是变量。任何字符串都可以来。像 。所以我们不能使用静态字符串来分割。
    【解决方案3】:

    使用.endsWith()

    if (!<abc/def>.endsWith(<abc>) {
       // do stuff ...
    }
    

    我放了!,所以它只发生在它不以

    结尾时

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      相关资源
      最近更新 更多