【发布时间】:2012-02-16 19:15:41
【问题描述】:
如何编写一个匹配由新行和空格分隔的多行的正则表达式?
以下代码适用于多行,但如果输入 是
String input = "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");
}
}
}
【问题讨论】:
-
看起来可行!给一些更具体的,会发生什么?应该发生什么?
-
嗨 Bhushan,即使输入由换行符分隔,匹配项也应返回匹配模式假设如果输入有多个换行符 A1234567890\nAAAAA\ndddd\ndddd\nddd,匹配项返回匹配项()找到什么都没有”
-
我复制并粘贴了您的代码并执行,我得到了这个输出:A1234567890 AAAAA*matches() 找到了从索引开始到索引结束的模式 ""