1

I have a String like this as shown below. From below string I need to extract number 123 and it can be at any position as shown below but there will be only one number in a string and it will always be in the same format _number_

text_data_123
text_data_123_abc_count
text_data_123_abc_pqr_count

text_tery_qwer_data_123
text_tery_qwer_data_123_count
text_tery_qwer_data_123_abc_pqr_count

Below is the code:

String value = "text_data_123_abc_count";   

// this below code will not work as index 2 is not a number in some of the above example
int textId = Integer.parseInt(value.split("_")[2]);

What is the best way to do this?

1
  • You should define "best". You could use a regexp or a removal Commented Aug 12, 2015 at 18:17

5 Answers 5

1

With a little guava magic:

String value = "text_data_123_abc_count";
Integer id = Ints.tryParse(CharMatcher.inRange('0', '9').retainFrom(value)

see also CharMatcher doc

Sign up to request clarification or add additional context in comments.

Comments

1
\\d+

this regex with find should do it for you.

1 Comment

@ThaNet: This is Java, not C#.
1

Use Positive lookahead assertion.

Matcher m = Pattern.compile("(?<=_)\\d+(?=_)").matcher(s);
while(m.find()) 
{
System.out.println(m.group());
}

Comments

1

You can use replaceAll to remove all non-digits to leave only one number (since you say there will be only 1 number in the input string):

String s = "text_data_123_abc_count".replaceAll("[^0-9]", "");

See IDEONE demo

Instead of [^0-9] you can use \D (which also means non-digit):

String s = "text_data_123_abc_count".replaceAll("\\D", "");

Given current requirements and restrictions, the replaceAll solution seems the most convenient (no need to use Matcher directly).

Comments

0

u can get all parts from that string and compare with its UPPERCASE, if it is equal then u can parse it to a number and save:

public class Main {

public static void main(String[] args) {

    String txt = "text_tery_qwer_data_123_abc_pqr_count";

    String[] words = txt.split("_");

    int num = 0;

    for (String t : words) {
        if(t == t.toUpperCase())
            num = Integer.parseInt(t);
    }

    System.out.println(num);
}

}

2 Comments

This will fail in case there is a word in ALLCAPS.
then u can edit the if: if(t == t.toUpperCase() && t == t.toLowerCase()) all is part of the imagination...

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.