[英]Java replaceAll Regex for special character [
我遇到了正则表达式表达问题。 需要正则表达式专家的帮助! 这很简单,但是我无法正常工作。
我知道是否要检查文本的开头,我应该使用^和文本的结尾,我应该使用$
我想将[quote]
替换为<a>quote</a>
。
这似乎不起作用..
String test = "this is a [quote]"
test.replaceAll("^\\[", "<a>");
test.replaceAll("\\]$", "</a>");
我希望字符串变为"this is a <a>quote</a>"
..
如果要用成对替换[
和]
,则需要一次替换它们。
String test = "this [test] is a [quote]";
String result = test.replaceAll("\\[([^\\]]+)\\]", "<a>$1</a>");
^
表示您正在字符串的开头寻找内容。 但是[
不会出现在字符串的开头,因此您将没有匹配项。 做就是了:
test.replaceAll("\\[", "<a>");
test.replaceAll("\\]", "</a>");
同样,您不能就地修改字符串。 您必须将输出分配给某些东西。 你可以做:
test = test.replaceAll("\\[", "<a>").replaceAll("\\]", "</a>");
那就是如果您仍然想使用变量test
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.