开发者

How to parse a string in Java? Is there anything similar to Python's re.finditer()?

开发者 https://www.devze.com 2023-01-16 14:05 出处:网络
I have an 开发者_高级运维input string with a very simple pattern - capital letter, integer, capital letter, integer, ...and I would like to separate each capital letter and each integer. I can\'t figu

I have an 开发者_高级运维input string with a very simple pattern - capital letter, integer, capital letter, integer, ... and I would like to separate each capital letter and each integer. I can't figure out the best way to do this in Java.

I have tried regexp using Pattern and Matcher, then StringTokenizer, but still without success.

This is what I want to do, shown in Python:

for token in re.finditer( "([A-Z])(\d*)", inputString):
      print token.group(1)
      print token.group(2)

For input "A12R5F28" the result would be:

A

12

R

5

F

28


You could use regex API in Java and achieve the same functionality:

Pattern myPattern = Pattern.compile("([A-Z])(\d+)")
Matcher myMatcher = myPattern.matcher("A12R5F28");
while (myMatcher.find()) {
      // Do your stuff here
}


Expanding on Ravi's Answer....

Pattern myPattern = Pattern.compile("([A-Z])(\\d+)");
Matcher myMatcher = myPattern.matcher("A12R5F28");
while (myMatcher.find()) {
  System.out.println(myMatcher.group(1) + "\n" + myMatcher.group(2));
}
0

精彩评论

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