首页 > 解决方案 > 正则表达式中是否有任何 NOT 运算符

问题描述

细绳 :

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

使用正则表达式:(<.*?>)

我能够得到像 <ex id=\"3\"/>和 这样的标签<g id=\"4\">

但是我们如何从句子中删除所有字符串部分,以便最终字符串看起来像<ex id=\"3\"/><g id=\"4\"></g><g id=\"5\">

只有标签。

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

标签: javaregexstringtags

解决方案


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

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\">

推荐阅读