Azfaar kabir Siddiqui
Azfaar kabir Siddiqui

Reputation: 780

How to extract numbers from a string

String a = "sin(23)+cos(4)+2!+3!+44!";
a.replaceAll("\D"); //Not working it is only extracting Digits 

I want to extract the numbers which are with ! only (example 2 and 3), then have to save it in a int[] and have to again paste those numbers at the place where 2! and 3! exist.

Upvotes: 0

Views: 174

Answers (2)

ADTC
ADTC

Reputation: 10086

Use regular expression to find what you want:

String a = "sin(23)+cos(4)+2!+3!+44!";

Pattern pattern = Pattern.compile("\\d+!"); //import java.util.regex.Pattern
Matcher matcher = pattern.matcher(a);       //import java.util.regex.Matcher
while (matcher.find()) {
    System.out.print("Start index: " + matcher.start());
    System.out.print(" End index: " + matcher.end() + " -> ");
    System.out.println(matcher.group());
}

Output:

Start index: 15 End index: 17 -> 2!
Start index: 18 End index: 20 -> 3!
Start index: 21 End index: 24 -> 44!

Further improvement:

With the following, you can cast the matcher.group(1) return value directly using Integer.parseInt():

Pattern pattern = Pattern.compile("(\\d+)!");
...
    System.out.println(matcher.group(1));

Output:

Start index: 15 End index: 17 -> 2
Start index: 18 End index: 20 -> 3
Start index: 21 End index: 24 -> 44

Can you figure out the rest? You could use the index values to replace the matches in the original string, but be sure to start from the last one.

Upvotes: 4

Pshemo
Pshemo

Reputation: 124225

First thing: Strings are immutable. You code you tried should be more like

a = a.replaceAll("\\D",""); 

Second, if you are sure that you will not have more complext expressions like ((1+2)!+3)! then you can use appendReplacement and appendTail methods from Matcher class.

String a = "sin(23)+cos(4)+2!+3!+44!";

StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile("(\\d+)!");
Matcher m = p.matcher(a);
while(m.find()){
    String number = m.group(1);//only part in parenthesis, without "!"
    m.appendReplacement(sb, calculatePower(m.group(number )));
}
m.appendTail(sb);
a = sb.toString();

Upvotes: 5

Related Questions