正则表达式:符合一定规则的字符串。 一般不常用。但要是用起来,却能解决大问题。在这里对正则表达式整理一下。
A compiled rePResentation of a regular expression. 正则表达式的编译表现形式。
A regular expression, specified as a string, must first be compiled into an instance of this class. The resulting pattern can then be used to create a Matcher object 正则表达式首先要被编译为Pattern类的对象。可以通过编译后的Pattern对象创建匹配器Matcher对象。该Matcher对象可以用来匹配字符串。
An engine that performs match Operations on a character sequence by interpreting a Pattern. 通过该指定Pattern的匹配引擎可以对一个字符串进行多种匹配操作,有如下几种:
The matches method attempts to match the entire input sequence against the pattern. 匹配整个字符串,matches()方法。
The lookingAt method attempts to match the input sequence, starting at the beginning, against the pattern. 始终从头开头匹配,找到为止。lookingAt()方法。
The find method scans the input sequence looking for the next subsequence that matches the pattern. 每次重置,从指定index开始查找。常和group()方法连用。
java Pattern Java Matcher Android Pattern Android Matcher
String类中,正则表达式源码全都按照此步骤,最终都调用Matcher类方法。 可查看源码更详细获知。
//把正则表达式编译成模式对象Pattern Pattern p = Pattern.compile("a*b"); //通过模式对象生成相应的匹配器 Matcher m = p.matcher("aaaaab"); //调用方法进行匹配 boolean b = m.matches();查看API文档,得知更详细的写法。这里列出常用的。
规则 | 含义 |
字符Characters: | |
x | The character x,字符x |
// | The backslash character,反斜线 |
/n | The newline (line feed) character (‘/u000A’),另起一行 |
/r | The carriage-return character (‘/u000D’),回车 |
字符类Character classes: | |
[abc] | a, b, or c。 a,b,或者c |
[^abc] | Any character except a, b, or c (negation)。除了a,b,c |
[a-zA-Z] | a through z or A through Z, inclusive (range)。所有的英文字母 |
预定义字符类Predefined character classes: | |
. | Any character,通配符。 /.表示字符串 |
/d | A digit: [0-9]。所有数字 |
/D | A non-digit: [^0-9]。非数字 |
/s | A whitespace character: [ /t/n/x0B/f/r]。所有空字符 |
/w | A Word character: [a-zA-Z_0-9]。所有的英文字母和阿拉伯数据,和下划线。 |
边界匹配Boundary matchers: | |
^ | The beginning of a line。开头 |
$ | The end of a line。结尾 |
/b | A word boundary。单词边界。/b详解 |
数量词Greedy quantifiers: | |
X? | X, once or not at all。至多0次 |
X* | X, zero or more times。至少0次 |
X+ | X, one or more times。至少1次。 |
X+ | X, one or more times。至少1次。 |
X{n} | exactly n times。只有n次。 |
X{n,} | X, at least n times。至少n次。 |
X{n,m} | X, at least n but not more than m times。至少n次,不超过m次。 |
新闻热点
疑难解答