[英]Remove data between two strings
I have to remove data between two string as below 我必须删除两个字符串之间的数据,如下所示
<PACKET>752</PACKET> <TIME>23-Oct-2013 12:05:46 GMT Standard Time</TIME> <INTERVAL>2</INTERVAL> <HEADER>hi this should not be printed only</HEADER> <DATA></DATA>
In this I have to remove data between <HEADER> and
</HEADER> .
在此,我必须删除<HEADER>和
</ HEADER>之间的数据。
Can any body give me regex for this? 有人可以为此给我正则表达式吗?
I think this can do the job with RegEx: 我认为这可以通过RegEx做到:
String str="b1<HEADER>aaaaa</HEADER>b2";
String newstring = str.replaceAll("<HEADER[^>]*>([^<]*)<\\/HEADER>", "");
System.out.println(newstring);
This prints b1b2
打印
b1b2
In the case that you have other tags inside <HEADER>
the above will fail. 如果
<HEADER>
还有其他标签,则上述操作将失败。 Consider the below example : 考虑以下示例:
String str = "b1<HEADER>aa<xxx>xx</xxx>aaa</HEADER>b2";
String newstring = str.replaceAll("<HEADER[^>]*>([^<]*)<\\/HEADER>", "");
System.out.println(newstring);
This prints: b1<HEADER>aa<xxx>xx</xxx>aaa</HEADER>b2
打印:
b1<HEADER>aa<xxx>xx</xxx>aaa</HEADER>b2
To overcome this and remove also the containing tags use this: 为了克服这一点并删除包含的标签,请使用以下命令:
newstring = str.replaceAll("<HEADER.+?>([^<]*)</HEADER>", "");
This will print b1b2
. 这将打印
b1b2
。
Maroun's right that it's not a good idea, but if you have to do it then this might work: Maroun认为这不是一个好主意,但是如果必须这样做,那么这可能会起作用:
(?ms)(.*<HEADER>).*(<\/HEADER>.*)
This captures everything up to and including <HEADER>
in group 1, and everything from </HEADER>
onwards in group 2. You can then concatenate the two to remove the bit in the middle. 这将捕获直到第1组中的
<HEADER>
以及包括第2组中</HEADER>
所有内容。然后,可以将两者串联以除去中间的位。
See here: http://regex101.com/r/bC2eQ7 看到这里: http : //regex101.com/r/bC2eQ7
This RegEx replaces everything inside the tag with en empty String: 此RegEx用空字符串替换标签内的所有内容:
String input = "<PACKET>752</PACKET>...<HEADER>hi this should be printed only</HEADER><DATA></DATA>";
String output = input.replaceAll("(?<=<HEADER>).*?(?=</HEADER>)", "");
Result: 结果:
<PACKET>752</PACKET>...<HEADER></HEADER><DATA></DATA>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.