开发者

Java Regular Expression processing

if I have a text

R 26 bla bla bla bla R 25 bla bla R 25/30 bla bla bla S 30/50/30 bla bla

and I have a regex

[RS] (\\d+|\\d+/\\d+|\\d+/\\d+/\\d+) 

which will match the bold data ... now , I want a code that returns for me the bold expressions + the following data.

For example , I want the following pairs:

R 26 : bla bla bla bla
R 25 : bla bla
R 25/30 : bla bla bla
S 30/50/30 : bla bla
开发者_开发问答

may be this image will be clearer :

  • http://i.stack.imgur.com/xMerw.png


Here you go!

Pattern pattern = Pattern.compile("([RS] (\\d+|\\d+/\\d+|\\d+/\\d+/\\d+)) ([^RS]*)");

Matcher matcher = pattern.matcher("R 26 bla bla bla bla R 25 bla bla R 25/30 bla bla bla S 30/50/30 bla bla");

while(matcher.find()) {
    System.out.println(matcher.group(1) + " " + matcher.group(3));
}


The order of the alternatives is important. With your original regex, the second and third alternatives will never match. Reversing their order fixes the problem like so:

Pattern regex = Pattern.compile("([RS] (\\d+/\\d+/\\d+|\\d+/\\d+|\\d+)) ([^RS]*)");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜