2012年1月9日星期一

java正则匹配任意字符(包括换行回车)

ref
以下为正确的正则表达式匹配规则:([\s\S]*)
同时,也可以用 “([\d\D]*)”、“([\w\W]*)” 来表示。
Pattern p=Pattern.compile(".*([\\s\\S]*)");
 /**
     * Enables dotall mode.
     *
     * 

In dotall mode, the expression . matches any character, * including a line terminator. By default this expression does not match * line terminators. * *

Dotall mode can also be enabled via the embedded flag * expression (?s). (The s is a mnemonic for * "single-line" mode, which is what this is called in Perl.)

*/ String s="balabala\r\n\tsomehead\r\n\t\r\n\t\r\n\t\r\n"; Pattern p=Pattern.compile(".*(.*)",Pattern.DOTALL); Matcher m = p.matcher(s); if (m.find()) { String matchedText = m.group(); int matchedFrom = m.start(); int matchedTo = m.end(); System.out.println("matched [" + matchedText + "] " + "from " + matchedFrom + " to " + matchedTo + "."+ m.group(1)); } else { System.out.println("didn't match"); }

没有评论:

发表评论