简体   繁体   English

替换Java字符串中的正则表达式

[英]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: 马克的答案会起作用,但可以通过两个简单的更改来改进:

  • The central parentheses are redundant if you're not using that group. 如果您不使用该组,则中央括号是多余的。
  • Making it non-greedy will help if you have multiple my:string tags to match. 如果您要匹配多个my:string标记,则将其设置为非贪婪会有所帮助。

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教程,并检出字符类和捕获组。

The PCRE would be: PCRE为:

/invalid_content/

For a simple substitution. 对于一个简单的替代。 What more do you want? 您还想要什么?

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.

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