简体   繁体   English

使用String的replaceAll方法删除所有标记,除非它们遵循特定的短语

[英]Use String's replaceAll method to remove all tokens unless they follow a specific phrase

I have a need to replace a particular token (in this case, ? ) with another token (we can start with ! or something). 我需要用另一个标记(我们可以以!或其他开头)替换特定的标记(在这种情况下为? )。 String's replaceAll method will work for this. 字符串的replaceAll方法将对此起作用。 But, I don't want to replace the question mark if it happens to follow the token action . 但是,如果它恰好跟随令牌action ,我不想替换问号。 (That would be bad!) (那太糟糕了!)

I've tried text = text.replaceAll("[^a][^c][^t][^i][^o][^n]\\\\?","!"); 我试过了text = text.replaceAll("[^a][^c][^t][^i][^o][^n]\\\\?","!"); but that didn't work. 但这没用。

For example, I want "test.action?param=lol?omg"; 例如,我想要"test.action?param=lol?omg"; to turn into test.action?param=lol!omg . 变成test.action?param=lol!omg I know I could do something silly like 我知道我可以做一些愚蠢的事情

text.replaceAll("action\\?","%%%CRAZYTOKEN%%%")
    .replaceAll("\\?","!")
    .replaceAll("%%%CRAZYTOKEN%%%","action?");

but that just seems like a waste of time, especially on large strings. 但这似乎是浪费时间,尤其是在大弦上。 I'd rather do it right. 我宁愿做对。

You need a negative look behind 您需要背后的负面印象

text.replaceAll("(?<!action)\\?", "!");

This asserts that the ? 这断言? does not follow action 遵循action

Just use a zero-width negative lookbehind assertion to only match ? 只需使用零宽度的负向后声明就可以匹配? s which don't follow action : 遵循action

text = text.replaceAll("(?<!action)\\?", "!");

Note the extra \\\\ before the ? 注意在?之前的多余\\\\ ? . You need to escape the ? 您需要逃脱? since it is a special character in regex. 因为它是正则表达式中的特殊字符。

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

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