Java 正则表达式中是否有NOT运算符
字符串:Java 正则表达式中是否有NOT运算符,java,regex,string,tags,Java,Regex,String,Tags,字符串: The car has <ex id=\"3\"/><g id=\"4\">attributes</g><g id=\"5\">, such as weight and color 使用正则表达式: 我能得到像和这样的标签 但是我们怎样才能从句子中删除所有的字符串部分,使最后的字符串看起来像这样呢 只有标签 Q:删除句子中的任何内容,但标记不是标记的运算符。下面的代码使用所需的
The car has <ex id=\"3\"/><g id=\"4\">attributes</g><g id=\"5\">, such as weight and color
使用正则表达式:
我能得到像和这样的标签
但是我们怎样才能从句子中删除所有的字符串部分,使最后的字符串看起来像这样呢
只有标签
Q:删除句子中的任何内容,但标记不是标记的运算符。下面的代码使用所需的标记创建一个新字符串
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\">
下面的代码使用所需的标记创建一个新字符串
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\">
输出:
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的建议时,此代码段起作用,只获取字符串中存在的标记
输出:
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的建议时,此代码段起作用,仅获取字符串中存在的标记。在Matcher.group0中使用相同的正则表达式查找并获取新字符串。使用Matcher.group0在Matcher中使用相同的正则表达式。使用Matcher.group0查找并获取新字符串