【问题标题】:Is there any NOT operator in Regex正则表达式中是否有任何 NOT 运算符
【发布时间】:2021-02-09 07:15:58
【问题描述】:

字符串:

The car has <ex id=\"3\"/><g id=\"4\">attributes</g><g id=\"5\">, such as weight and color

使用正则表达式:(&lt;.*?&gt;)

我能够得到像 &lt;ex id=\"3\"/&gt;&lt;g id=\"4\"&gt; 这样的标签

但是我们怎样才能从句子中删除所有字符串部分,以便最终的字符串看起来像&lt;ex id=\"3\"/&gt;&lt;g id=\"4\"&gt;&lt;/g&gt;&lt;g id=\"5\"&gt;

只有标签。

问:从句子中删除除标签以外的任何内容(标签的 NOT 运算符)。

【问题讨论】:

  • Matcher.find() 中使用相同的正则表达式并使用matcher.group(0) 获取新字符串

标签: java regex string tags


【解决方案1】:

以下代码创建一个带有所需标签的新字符串。

public static void main(String[] args)
{
    String line = "The car has <ex id=\\\"3\\\"/><g id=\\\"4\\\">attributes</g><g id=\\\"5\\\">, such as weight and color";
    String regex = "(<.*?>)";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(line);
    StringBuilder compactline = new StringBuilder();
    while (matcher.find()) {
        compactline.append(matcher.group());
    }
    System.out.println("Original Line : " + line);
    System.out.println("Compact Line : " + compactline);
}

输出

Original Line : The car has <ex id=\"3\"/><g id=\"4\">attributes</g><g id=\"5\">, such as weight and color

Compact Line : <ex id=\"3\"/><g id=\"4\"></g><g id=\"5\">

【讨论】:

    【解决方案2】:
    String  segment ="The car has <ex id=\"3\"/><g id=\"4\">attributes</g><g id=\"5\">, such as weight and color;
    String regex="(<.*?>)";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher=pattern.matcher(segment);
       while(matcher.find())
          {
            System.out.println("matcher ="+matcher.group());
          }
    

    输出:

    matcher =<ex id=\"3\"/>
    matcher =<g id=\"4\">
    matcher =</g>
    matcher =<g id=\"5\">
    matcher =</g>
    matcher =<g id=\"6\">
    matcher =</g>
    matcher =<g id=\"7\">
    matcher =</g>
    

    在尝试@anubhava 的建议时,此代码 sn-p 工作并仅获取字符串中存在的标签。

    【讨论】:

      猜你喜欢
      • 2010-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-29
      • 2012-10-30
      相关资源
      最近更新 更多