1

i need to extract the numbers alone from this text i use sub string to extract the details some times the number decreases so i am getting an error value...

 example(16656);

4 Answers 4

3

Use Pattern to compile your regular expression and Matcher to get a particular captured group. The regex I'm using is:

example\((\d+)\)

which captures the digits (\d+) within the parentheses. So:

Pattern p = Pattern.compile("example\\((\\d+)\\)");
Matcher m = p.matcher(text);
if (m.find()) {
  int i = Integer.valueOf(m.group(1));
  ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

look at Java Regular Expression sample here:

http://java.sun.com/developer/technicalArticles/releases/1.4regex/

specially focus on find method.

Comments

0
String yourString = "example(16656);";

Pattern pattern = Pattern.compile("\\w+\\((\\d+)\\);");
Matcher matcher = pattern.matcher(yourString);
if (matcher.matches())
{
    int value = Integer.parseInt(matcher.group(1));
    System.out.println("Your number: " + value);
}

Comments

0

I will suggest you to write your own logic to do this. Using Pattern and Matcher things from java are good practice but these are standard solutions and may not suit as a solution in effective manner always. Like cletus provided a very neat solution but what happens in this logic is that a substring matching algorithm is performed in the background to trace digits. You do not need the pattern finding here I suppose. You just need to extract the digits from a string (like 123 from "a1b2c3") .See the following code which does it in clean manner in O(n) and does not perform unnecessary extra operation as Pattern and Matcher classes do for you (just do copy and paste and run :) ):

public class DigitExtractor {

/**
 * @param args
 */
public static void main(String[] args) {

    String sample = "sdhj12jhj345jhh6mk7mkl8mlkmlk9knkn0";

    String digits = getDigits(sample);

    System.out.println(digits);
}

private static String getDigits(String sample) {

    StringBuilder out = new StringBuilder(10);

    int stringLength = sample.length();

    for(int i = 0; i <stringLength ; i++)
    {
        char currentChar = sample.charAt(i);
        int charDiff = currentChar -'0';

        boolean isDigit = ((9-charDiff)>=0&& (9-charDiff <=9));

        if(isDigit)
            out.append(currentChar);

    }

    return out.toString();
}

}

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.