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的正则表达式的工具类库:java.util.regex

相关类: Pattern、Matcher

java的JDK API文档(谷歌翻译):

必须首先将正则表达式(指定为字符串)编译为此类的实例。然后将所得的图案可以被用来创建一个Matcher对象可以匹配任意character sequences针对正则表达式。 执行匹配的所有状态都驻留在匹配器中,所以许多匹配者可以共享相同的模式。

因此,典型的调用序列

Pattern p = Pattern.compile("a*b");

Matcher m = p.matcher("aaaaab");

boolean b = m.matches();这个类定义了一个matches方法,以便在正则表达式只使用一次时方便。 该方法编译一个表达式,并在单个调用中匹配输入序列。 该声明

boolean b = Pattern.matches("a*b", "aaaaab");相当于上面的三个语句,尽管对于重复匹配,它的效率较低,因为它不允许编译的模式被重用。

这个类的实例是不可变的,可以安全地被多个并发线程使用。该实例Matcher类不适合这样的使用是安全的。

翻译不咋的,但是关键的已经有了:

Pattern p = Pattern.compile("a*b");

Matcher m = p.matcher("aaaaab");

boolean b = m.matches();

大概意思就是通过Pattern.compile(String regex)创建一个正则表达式或者说是匹配模式,再通过Pattern.matcher(CharSequence input)方法得到Matcher对象

再看看Matcher类的一些方法:

我们通过正则表达式校验数据时则是通过marchers()方法,例如手机号:

String regex = "^(1[3-9]\\d{9}$)";
Pattern p =Pattern.compile(regex);
Matcher m = p.matcher("13300000000");
boolean matches = m.matches();

匹配字符串:

String regex = "abc";
Pattern p =Pattern.compile(regex);
Matcher m = p.matcher("abcdefg");
while (m.find())
{
    System.out.println(m.group());
}

匹配分组:

先上代码:

结果:

String regex = "(a)(b)(c)";
Pattern p =Pattern.compile(regex);
Matcher m = p.matcher("abcdefg");
while (m.find())
{
    System.out.println(m.group(0));
    System.out.println(m.group(1));
    System.out.println(m.group(2));
    System.out.println(m.group(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 = Pattern.compile(regex);
Matcher m = p.matcher(content);
while (m.find())
{
    System.out.println(m.group(0));
    System.out.println(m.group(1));
    System.out.println(m.group(2));
    System.out.println(m.group(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

哦吼!

猜你喜欢

转载自blog.csdn.net/qq_34928194/article/details/107483528
今日推荐