Java正则表达式replaceAll多行
我对多行字符串的replaceAll有问题:
String regex = "\\s*/\\*.*\\*/";
String testWorks = " /** this should be replaced **/ just text";
String testIllegal = " /** this should be replaced \n **/ just text";
testWorks.replaceAll(regex, "x");
testIllegal.replaceAll(regex, "x");
上面的内容适用于testWorks,但不适用于testIllegal!? 这是为什么?我该如何克服这个问题?我需要替换诸如跨多行的注释 /* ... */ 之类的内容。
I have a problem with the replaceAll for a multiline string:
String regex = "\\s*/\\*.*\\*/";
String testWorks = " /** this should be replaced **/ just text";
String testIllegal = " /** this should be replaced \n **/ just text";
testWorks.replaceAll(regex, "x");
testIllegal.replaceAll(regex, "x");
The above works for testWorks, but not for testIllegal!?
Why is that and how can I overcome this? I need to replace something like a comment /* ... */ that spans multiple lines.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要使用
Pattern.DOTALL
标志来表示点应该与换行符匹配。例如,或者使用
(?s)
在模式中指定标志,例如You need to use the
Pattern.DOTALL
flag to say that the dot should match newlines. e.g.or alternatively specify the flag in the pattern using
(?s)
e.g.将
Pattern.DOTALL
添加到编译中,或将(?s)
添加到模式中。这会起作用
参见
使用正则表达式匹配多行文本
Add
Pattern.DOTALL
to the compile, or(?s)
to the pattern.This would work
See
Match multiline text using regular expression
元字符
.
匹配除换行符之外的任何字符。这就是为什么您的正则表达式不适用于多行情况。要解决此问题,请将
.
替换为与任何字符(包括换行符)匹配的[\d\D]
。实际代码
The meta character
.
matches any character other than newline. That is why your regex does not work for multi line case.To fix this replace
.
with[\d\D]
that matches any character including newline.Code In Action