如何编写一个正则表达式来匹配由换行符和空格分隔的多行?
以下代码适用于多行,但如果输入 是
字符串输入=“A1234567890\nAAAAA\nwwwwwwww”
我的意思是 matches()
对于输入来说不正确。
这是我的代码:
package patternreg;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class pattrenmatching {
public static void main(String[] args) {
String input = "A1234567890\nAAAAA";
String regex = ".*[\\w\\s\\w+].*";
Pattern p = Pattern.compile(regex,Pattern.MULTILINE);
Matcher m =p.matcher(input);
if (m.matches()) {
System.out.println("matches() found the pattern \""
+ "\" starting at index "
+ " and ending at index ");
} else {
System.out.println("matches() found nothing");
}
}
}
最佳答案
您还可以添加 DOTALL 标志以使其正常工作:
Pattern p = Pattern.compile(regex, Pattern.MULTILINE | Pattern.DOTALL);
关于java正则表达式字符串匹配和多行用新行分隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9317591/