-2

I'm using this regular expression to parse a string like "CALENDAR YEAR: 2012".Can someone suggest a better one ? And I want to use matcher.find() (CALENDAR YEAR:\\s+)?((2\\d\\d\\d))

I want to get 2012 in a group.

I can't understand why it prints null when i do this:

 while (myMatcher.find()) {
     System.out.println(myMatcher.group(1));
     System.out.println(myMatcher.group(2));

    }



CALENDAR YEAR: 
2012
null
null

EDIT: How will I change the expression if the code is using matches and i Still want to parse the year out of the string?

4

2 回答 2

0

您根本不需要使用额外的组 - 使用正则表达式模式

(?<=CALENDAR YEAR: )2\\d{3}(?!\\d)

...结果将在

myMatcher.group(0)
于 2012-11-15T21:11:45.753 回答
0

阅读正则表达式手册

显然,您不知道何时使用该?角色,何时不使用。或者什么时候使用()...

你可以离开它。

CALENDAR YEAR:\s+(\d{4})

应该已经成功了。但是您只是将随机字符放入您的正则表达式中,而不是查看周围的各种示例。

于 2012-11-15T20:32:24.177 回答