简体   繁体   English

如何在Java中解析字符串? 是否有类似Python的re.finditer()?

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

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. 我无法弄清楚在Java中执行此操作的最佳方法。

I have tried regexp using Pattern and Matcher, then StringTokenizer, but still without success. 我已经使用Pattern和Matcher,然后使用StringTokenizer尝试了regexp,但仍然没有成功。

This is what I want to do, shown in Python: 这就是我想要做的,用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: 对于输入“A12R5F28”,结果将是:

A

12

R

5

F

28

You could use regex API in Java and achieve the same functionality: 您可以在Java中使用regex API并实现相同的功能:

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

Expanding on Ravi's Answer.... 扩展Ravi的答案....

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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM