java利⽤正则表达式获取字符串中某两个字符之间的内容昨天遇到⼀个"赞美之词"的报⽂数据需要解析,它⼤概长这个样⼦:
{
"id",
"name",
[{1,1,2},{2,1,2},{3,1,2},{4,1,2}],
[
{"iid","nname",[0,1]},
{"iid","nname",[2,3]}
],
[1,2,3,4]
}
乍⼀看像是json,so easy,
仔细⼀看:
Are you crazy?
思考⼀下:
没事,⼩问题
通过split(",",3)分割字符串,取id、name和[]
......
[{},{},{}]通过正则表达式取
那么,来了:
java的正则表达式的⼯具类库:
相关类: Pattern、Matcher
java的JDK API⽂档(⾕歌翻译):
必须⾸先将正则表达式(指定为字符串)编译为此类的实例。然后将所得的图案可以被⽤来创建⼀个Matcher对象可以匹配任意character sequences针对正则表达式。执⾏匹配的所有状态都驻留在匹配器中,所以许多匹配者可以共享相同的模式。
因此,典型的调⽤序列
Pattern p = Patternpile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();这个类定义了⼀个matches⽅法,以便在正则表达式只使⽤⼀次时⽅便。该⽅法编译⼀个表达式,并在单个调⽤中匹配输⼊序列。该声明
boolean b = Pattern.matches("a*b", "aaaaab");相当于上⾯的三个语句,尽管对于重复匹配,它的效率较低,因为它不允许编译的模式被重⽤。
这个类的实例是不可变的,可以安全地被多个并发线程使⽤。该实例Matcher类不适合这样的使⽤是安全的。
翻译不咋的,但是关键的已经有了:
Pattern p = Patternpile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
⼤概意思就是通过Patternpile(String regex)创建⼀个正则表达式或者说是匹配模式,再通过Pattern.matcher(CharSequence input)⽅法得到Matcher对象
再看看Matcher类的⼀些⽅法:
我们通过正则表达式校验数据时则是通过marchers()⽅法,例如⼿机号:
String regex = "^(1[3-9]\\d{9}$)";
Pattern p =Patternpile(regex);
Matcher m = p.matcher("133********");
boolean matches = m.matches();
匹配字符串:
String regex = "abc";
Pattern p =Patternpile(regex);
Matcher m = p.matcher("abcdefg");
while (m.find())
{
System.out.up());
}
匹配分组:
先上代码:
结果:
String regex = "(a)(b)(c)";
Pattern p =Patternpile(regex);
Matcher m = p.matcher("abcdefg");
while (m.find())
{
System.out.up(0));
System.out.up(1));
System.out.up(2));
System.out.up(3));
}
abc
a正则表达式获取括号内容
b
c
在regex中,被()包裹的称为⼦序列,m.group(0)返回整个序列,相当于m.group()
⼦序列下标从1开始,若没有⼦序列,使⽤m.group(1)时则会出现IndexOutOfBoundsException
那现在回到最开始的问题,我要取[{},{},{}]中{}包裹的数据:
String regex = "\\{(.*?),(.*?),(.*?)\\}";
String content = "[{1,1,2},{2,1,2},{3,1,2},{4,1,2}]";
Pattern p = Patternpile(regex);
Matcher m = p.matcher(content);
while (m.find())
{
System.out.up(0));
System.out.up(1));
System.out.up(2));
System.out.up(3));
}
结果:
{1,1,2}
1
1
2
{2,1,2}
2
1
2
{3,1,2}
3
1
2
{4,1,2}
4
1
2
哦吼!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论