[英]replacing regex in java string
I have this java string: 我有这个java字符串:
String bla = "<my:string>invalid_content</my:string>";
How can I replace the "invalid_content" piece? 如何替换“ invalid_content”部分?
I know I should use something like this: 我知道我应该使用这样的东西:
bla.replaceAll(regex,"new_content");
in order to have: 为了有:
"<my:string>new_content</my:string>";
but I can't discover how to create the correct regex 但我找不到如何创建正确的正则表达式
help please :) 请帮助 :)
你可以做类似的事情
String ResultString = subjectString.replaceAll("(<my:string>)(.*)(</my:string>)", "$1whatever$3");
Mark's answer will work, but can be improved with two simple changes: 马克的答案会起作用,但可以通过两个简单的更改来改进:
Giving: 给予:
String ResultString = SubjectString.replaceAll
( "(<my:string>).*?(</my:string>)" , "$1whatever$2" );
But that's still not how I'd write it - the replacement can be simplified using lookbehind and lookahead, and you can avoid repeating the tag name, like this: 但这还不是我写的方式-可以使用lookbehind和lookahead简化替换,并且可以避免重复标签名称,如下所示:
String ResultString = SubjectString.replaceAll
( "(?<=<(my:string)>).*?(?=</\1>)" , "whatever" );
Of course, this latter one may not be as friendly to those who don't yet know regex - it is however more maintainable/flexible, so worth using if you might need to match more than just my:string tags. 当然,对于那些尚不知道正则表达式的人来说,后一种可能并不那么友好-但是它更易于维护/灵活,因此如果您可能需要匹配多个my:string标签,那么值得使用。
请参阅Java regex教程,并检出字符类和捕获组。
Is invalid_content
a fix value? invalid_content
是固定值吗? If so you could simply replace that with your new content using: 如果是这样,您可以使用以下内容将其替换为新内容:
bla = bla.replaceAll("invalid_content","new_content");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.