[英]Java regex replaceAll multiline
I have a problem with the replaceAll for a multiline string: 我对多行字符串的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");
The above works for testWorks, but not for testIllegal!? 以上适用于testWorks,但不适用于testIllegal !? Why is that and how can I overcome this? 为什么这样,我怎么能克服这个? I need to replace something like a comment /* ... */ that spans multiple lines. 我需要替换类似注释/ * ... * /的内容,它跨越多行。
You need to use the Pattern.DOTALL
flag to say that the dot should match newlines. 您需要使用Pattern.DOTALL
标志来表示该点应与新行匹配。 eg 例如
Pattern.compile(regex, Pattern.DOTALL).matcher(testIllegal).replaceAll("x")
or alternatively specify the flag in the pattern using (?s)
eg 或者使用(?s)
指定模式中的标志,例如
String regex = "(?s)\\s*/\\*.*\\*/";
Add Pattern.DOTALL
to the compile, or (?s)
to the pattern. 将Pattern.DOTALL
添加到模式,或(?s)
到模式。
This would work 这会奏效
String regex = "(?s)\\s*/\\*.*\\*/";
See Match multiline text using regular expression 请参阅使用正则表达式匹配多行文本
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. 与[\\d\\D]
匹配任何字符,包括换行符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.