正则表达式(RegEx / RegExp) 基本上,正则表达式是描述一定数量文本的模式。
^abc$ start / end of the string
\b \B word, not-word boundary
\w \d \s word, digit, whitespace
\W \D \S not word, digit, whitespace
\z - End of entire string
(…) - Grouping (capture groups)
[abc] any of a, b, or c
[^abc] not a, b, or c
[a-g] character between a & g
{ m,n } - quantifiers for “from m to n repetitions”
+ - quantifiers for 1 or more repetitions (i.e, {1,})
? - quantifiers for 0 or 1 repetitions (i.e, {0,1})
POSIX Bracket Expressions
POSIX 括号表达式是一种特殊的字符类。POSIX 括号表达式匹配一组字符中的一个字符,就像常规字符类一样。POSIX 字符类名称必须全部小写。POSIX 标准定义了 12 个字符类。下表列出了所有 12 个,以及一些 regex 风格也支持的[:ascii:]
和[:word:]
类。
使用正则表达式进行模式匹配:
final Pattern mix_alphaNumaric_pattern = Pattern.compile("^[A-Za-z0-9]+$");
final Pattern alphabets_pattern = Pattern.compile("^[A-Za-z,\\- ]+$");
final Pattern alphabetsNull_pattern = Pattern.compile("|^[A-Za-z,\\- ]+$");
final Pattern numaric_pattern = Pattern.compile("^[0-9]+$"); // ^begning +followed By $end
final Pattern date_time_pattern = Pattern.compile("\\d{1,2}/\\d{1,2}/\\d{4}\\s\\d{1,2}\\:\\d{1,2}");
final Pattern weather_pattern = Pattern.compile("[\\-]*\\d{1,3}\\.\\d{1,6}");
final Pattern email_pattern = Pattern.compile("^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$");
final Pattern mobile_pattern = Pattern.compile("(\\+)?(\\d{1,2})?\\d{10}");
public static void main(String[] args) {
String[] str = {"MCDL", "XMLIVD", "ABXMLVA", "XMLABCIX"};
Pattern p = Pattern.compile("^(M|D|C|L|X|V|I|i|v|x|l|c|d|m)+$");
// Returns: true if, and only if, the entire region sequence matches this matcher's pattern
for (String sequence : str ) {
boolean match = false, find = false;
if ( !p.matcher(sequence).matches() ) match = true;
if (p.matcher(sequence).find()) find = true;
System.out.format("%s \t Match[%s] Find[%s]\n", sequence, match, find);
}
}
输出:
MCDL Match[false] Find[true]
XMLIVD Match[false] Find[true]
ABXMLVA Match[true] Find[false]
XMLABCIX Match[true] Find[false]
@see 这个链接到: