简体   繁体   English

正则表达式模式匹配器

[英]Regex pattern matcher

I have a string : 154545K->12345K(524288K) 我有一个字符串: 154545K->12345K(524288K)

Suppose I want to extract numbers from this string. 假设我要从此字符串中提取数字。

The string contains the group 154545 at position 0 , 12345 at position 1 and 524288 at position 2 . 该字符串包含在位置0处的组154545 ,在位置1处的组12345和在位置2处的组524288

Using regex \\\\d+ , I need to extract 12345 which is at position 1 . 使用regex \\\\d+ ,我需要提取位置1处的12345

I am getting the desired result using this : 我正在使用此方法得到预期的结果:

String lString = "154545K->12345K(524288K)";
Pattern lPattern = Pattern.compile("\\d+");
Matcher lMatcher = lPattern.matcher(lString);
String lOutput = "";
int lPosition = 1;
int lGroupCount = 0;
while(lMatcher.find()) {
    if(lGroupCount == lPosition) {
    lOutput = lMatcher.group();
    break;
}
else {
    lGroupCount++;
}
}
System.out.println(lOutput);

But, is there any other simple and direct way to achieve this keeping the regex same \\\\d+ (without using the group counter)? 但是,还有其他简单而直接的方法来实现这一点, 使正则表达式保持\\\\d+相同 (不使用组计数器)吗?

尝试这个

String d1 = "154545K->12345K(524288K)".replaceAll("(\\d+)\\D+(\\d+).*", "$1");

If you expect your number to be at the position 1, then you can use find(int start) method like this 如果您希望数字位于位置1,则可以使用find(int start)方法

if (lMatcher.find(1) && lMatcher.start() == 1) {
    // Found lMatcher.group()
}

You can also convert your loop into for loop to get ride of some boilerplate code 您还可以将循环转换为for循环,以获得一些样板代码

String lString = "154540K->12341K(524288K)";
Pattern lPattern = Pattern.compile("\\d+");
Matcher lMatcher = lPattern.matcher(lString);


int lPosition = 2;
for (int i = 0; i < lPosition && lMatcher.find(); i++) {}

if (!lMatcher.hitEnd()) {
    System.out.println(lMatcher.group());
}

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

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