Mehran :
I have a problem getting char from string. 6xˆ3 + 5 + 10xˆ2, I have this as string and want to get the number after x^. How can I do this without using if and for? Is there any method and regex that can help me?
Arvind Kumar Avinash :
Do it as follows:
import java.util.Arrays;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
String exp = "6x^3 + 5 + 10x^2";
String[] nums = Pattern.compile("(?<=x\\^)[0-9]+").matcher(exp).results().map(MatchResult::group)
.toArray(String[]::new);
System.out.println(Arrays.toString(nums));
}
}
Output:
[3, 2]
Note: Matcher::results is available only since Java 9.
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=300313&siteId=1