1

I have a string : 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.

Using regex \\d+, I need to extract 12345 which is at position 1.

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)?

3
  • why dont you use matching groups and get result with backreferences ? Commented Mar 18, 2014 at 5:35
  • There is if you use capturing groups, however capturing groups start at 1, not 0 Commented Mar 18, 2014 at 5:35
  • Yes, if I use capturing groups, the regex will be "(\\d+)K->(\\d+)K((\\d+)K)" and I get "154545" at '1', "12345" at '2' and "524288" at '3'. But I need to keep the regex same, i.e "\\d+" only. Is there any alternative? Commented Mar 24, 2014 at 3:23

2 Answers 2

1

try this

String d1 = "154545K->12345K(524288K)".replaceAll("(\\d+)\\D+(\\d+).*", "$1");
Sign up to request clarification or add additional context in comments.

Comments

1

If you expect your number to be at the position 1, then you can use find(int start) method like this

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.