简体   繁体   English

Java从字符串中删除动态子字符串

[英]Java remove dynamic substring from string

I need to remove dynamic substring from string. 我需要从字符串中删除动态子字符串。 There is a few similar topic of this theme, but noone of them helped me. 这个主题有一些类似的主题,但是没有一个人帮助我。 I have a string eg: 我有一个字符串,例如:

product test1="001" test2="abc" test3="123xzy" 产品test1 =“ 001” test2 =“ abc” test3 =“ 123xzy”

and i need output: 我需要输出:

product test1="001" test3="123xzy" 产品test1 =“ 001” test3 =“ 123xzy”

I mean I need remove test2="abc". 我的意思是我需要删除test2 =“ abc”。 test2 is an unique element and can be placed anywhere in original string. test2是一个唯一元素,可以放在原始字符串的任何位置。 "abc" is dynamic variable and can have various length. “ abc”是动态变量,可以具有各种长度。 What is the fastest and the most elegant solution of this problem? 什么是最快,最优雅的解决方案? Thx 谢谢

You can use a regular expression: 您可以使用正则表达式:

String input = "product test1=\"001\" test2=\"abc\" test3=\"123xzy\"";
String result = input.replaceAll("test2=\".*?\"\\s+", "");

In substance: find a substring like test2="xxxxxx" , optionally followed by some spaces ( \\\\s+ ) and replace it with nothing. 本质上:找到一个像test2="xxxxxx"这样的子字符串,可以选择在其后跟一些空格( \\\\s+ ),然后将其替换为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM