简体   繁体   English

Java replaceAll正则表达式,用于特殊字符[

[英]Java replaceAll Regex for special character [

I am having regex expression problem. 我遇到了正则表达式表达问题。 need helps from regex experts! 需要正则表达式专家的帮助! It's fairly simple but I can't get it to work. 这很简单,但是我无法正常工作。

I know if I want to check the starting of a text, I should use ^ and ending of the text, I should use $ 我知道是否要检查文本的开头,我应该使用^和文本的结尾,我应该使用$

I want to replace [quote] to <a>quote</a> . 我想将[quote]替换为<a>quote</a>

This doesn't seems to work.. 这似乎不起作用..

String test = "this is a [quote]"
test.replaceAll("^\\[", "<a>");
test.replaceAll("\\]$", "</a>");

I want the string to become "this is a <a>quote</a>" .. 我希望字符串变为"this is a <a>quote</a>" ..

If you want to replace [ and ] with pair, you need to replace them in one time. 如果要用成对替换[] ,则需要一次替换它们。

String test = "this [test] is a [quote]";
String result = test.replaceAll("\\[([^\\]]+)\\]", "<a>$1</a>");

^ implies that you are looking for something at the beginning of the string. ^表示您正在字符串的开头寻找内容。 However [ does not appear at the beginning of the string, so you will not have a match. 但是[不会出现在字符串的开头,因此您将没有匹配项。 Just do: 做就是了:

test.replaceAll("\\[", "<a>");
test.replaceAll("\\]", "</a>");

Also, you cannot modify a String in-place. 同样,您不能就地修改字符串。 you'll have to assign the output to something. 您必须将输出分配给某些东西。 You can do: 你可以做:

test = test.replaceAll("\\[", "<a>").replaceAll("\\]", "</a>");

That is if you still want to use the variable test . 那就是如果您仍然想使用变量test

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

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