java - 正则表达式中是否有任何 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 运算符)。
解决方案
下面的代码创建一个带有所需标签的新字符串。
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\">
推荐阅读
- shell - 处理程序:xyz.lambda_handler 是一个文本,我希望 xyz.lambda_handler 作为使用 sh 脚本的输出
- sql-server - 将多个表中的多行用于具有标量 UDF 的持久计算列
- jmeter - 如何使用数组的长度来设置线程组中的线程数
- algorithm - 围绕对角线对矩阵元素进行排序
- python - 如何检查具有不同像素化的两张图像的相似性
- ubuntu-16.04 - 为 Mysql 5.6 & Ubuntu16.4 设置 binlog
- html - margin-bottom 和 vh 单位的问题
- javascript - 如何更新数组中的对象
- css - 如何在不丢失边框底部的情况下调整大小
- c - 在 main 中使用头文件中的结构(在 C 中)