Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher("There are more than -2 and less than 12 numbers here");
while (m.find()) {
System.out.println(m.group());
}
... prints -2 and 12.
-? matches a leading negative sign -- optionally. \d matches a digit, and we need to write \ as \\ in a Java String though. So, \d+ matches 1 or more digits.
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher("There are more than -2 and less than 12 numbers here");
while (m.find()) {
System.out.println(m.group());
}
... prints -2 and 12.
-? matches a leading negative sign -- optionally. \d matches a digit, and we need to write \ as \\ in a Java String though. So, \d+ matches 1 or more digits.
What about to use replaceAll java.lang.String method:
String str = "qwerty-1qwerty-2 455 f0gfg 4";
str = str.replaceAll("[^-?0-9]+", " ");
System.out.println(Arrays.asList(str.trim().split(" ")));
Output:
[-1, -2, 455, 0, 4]
Description
[^-?0-9]+
[and]delimites a set of characters to be single matched, i.e., only one time in any order^Special identifier used in the beginning of the set, used to indicate to match all characters not present in the delimited set, instead of all characters present in the set.+Between one and unlimited times, as many times as possible, giving back as needed-?One of the characters “-” and “?”0-9A character in the range between “0” and “9”
Java REGEX for only numbers - Stack Overflow
Extract number from string using regex in java - Stack Overflow
apex - How to find all numbers in a string using Regex - Salesforce Stack Exchange
Please help me with a RegEx to extract only the numbers from a string variable
Use this regex to select only numbers that aren't connected to any text
\b\d+\b
\d+allows any number of digits\bat the start and the end defines a word boundary so that it doesn't match words liketext12,9gag,4chanetc
Demo: https://regex101.com/r/Fzm2PS/2
// Will match 12, 34,
// Will not match text12, string, 9gag
What you want is a "positive look-behind" construct in your REGEX.
"[0-9]+(?<=[a-zA-Z])"
Matches:
the 9 in "a9";
the 10 in "B10";
the 9 in "a9A"
Doesn't Match:
the 9 in "9A";
the 10 in "+10"
the 10 in " 10"
Pattern.compile("-?[0-9]+(?:,[0-9]+)?")
Explanation
-? # an optional minus sign [0-9]+ # decimal digits, at least one (?: # begin non-capturing group , # the decimal point (German format) [0-9]+ # decimal digits, at least one ) # end non-capturing group, make optional
Note that this expression makes the decimal part (after the comma) optional, but does not match inputs like -,01.
If your expected input always has both parts (before and after the comma) you can use a simpler expression.
Pattern.compile("-?[0-9]+,[0-9]+")
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NumRegEx {
public static void main( String[] args ) {
String inputline = "\"Neuer Kontostand\";\"+2.117,68\"";
Pattern p = Pattern.compile(".*;\"(\\+|-)?([0-9.,]+).*");
Matcher m = p.matcher( inputline );
if( m.matches()) { // required
String sign = m.group( 1 );
String value = m.group( 2 );
System.out.println( sign );
System.out.println( value );
}
}
}
Output:
+
2.117,68
You need to call matcher.find() recursively until it returns false. Use a do/while block.
String str = '123-456/7890';
Pattern p = Pattern.compile('(\\d+)');
Matcher m = p.matcher( str );
if(m.find()) {
do {
system.debug( '-->>' + m.group() );
} while(m.find());
}
If you want to separate all the numbers into separate strings you can do the following.
String numsplit = str.replaceAll('[^0-9]+', ';');
list<String> nums = numsplit.split(';');
If you also want to extract the other characters there is a built-in splitbycharactertype method.
p = Pattern.compile("\\d{10}"); this matches 10 digits but your text "1234568asdjhgsd" only has 7 digits. You can use Pattern.compile("\\d{7}"); and it'll work. But number of digits always has to be <= 7.
print it if matches digits.
String str = "1234568asdjhgsd";
Pattern p;
p = Pattern.compile("\\d");
Matcher m;
m = p.matcher(str);
while (m.find()){
String xxx = m.group();
System.out.print(xxx);
}
Try
String regex = "[0-9]+";
or
String regex = "\\d+";
As per Java regular expressions, the + means "one or more times" and \d means "a digit".
Note: the "double backslash" is an escape sequence to get a single backslash - therefore, \\d in a java String gives you the actual result: \d
References:
Java Regular Expressions
Java Character Escape Sequences
Edit: due to some confusion in other answers, I am writing a test case and will explain some more things in detail.
Firstly, if you are in doubt about the correctness of this solution (or others), please run this test case:
String regex = "\\d+";
// positive test cases, should all be "true"
System.out.println("1".matches(regex));
System.out.println("12345".matches(regex));
System.out.println("123456789".matches(regex));
// negative test cases, should all be "false"
System.out.println("".matches(regex));
System.out.println("foo".matches(regex));
System.out.println("aa123bb".matches(regex));
Question 1:
Isn't it necessary to add
^and$to the regex, so it won't match "aa123bb" ?
No. In java, the matches method (which was specified in the question) matches a complete string, not fragments. In other words, it is not necessary to use ^\\d+$ (even though it is also correct). Please see the last negative test case.
Please note that if you use an online "regex checker" then this may behave differently. To match fragments of a string in Java, you can use the find method instead, described in detail here:
Difference between matches() and find() in Java Regex
Question 2:
Won't this regex also match the empty string,
""?*
No. A regex \\d* would match the empty string, but \\d+ does not. The star * means zero or more, whereas the plus + means one or more. Please see the first negative test case.
Question 3
Isn't it faster to compile a regex Pattern?
Yes. It is indeed faster to compile a regex Pattern once, rather than on every invocation of matches, and so if performance implications are important then a Pattern can be compiled and used like this:
Pattern pattern = Pattern.compile(regex);
System.out.println(pattern.matcher("1").matches());
System.out.println(pattern.matcher("12345").matches());
System.out.println(pattern.matcher("123456789").matches());
You can also use NumberUtil.isNumber(String str) from Apache Commons
You can use regex and delete non-digits.
str = str.replaceAll("\\D+","");
Here's a more verbose solution. Less elegant, but probably faster:
public static String stripNonDigits(
final CharSequence input /* inspired by seh's comment */){
final StringBuilder sb = new StringBuilder(
input.length() /* also inspired by seh's comment */);
for(int i = 0; i < input.length(); i++){
final char c = input.charAt(i);
if(c > 47 && c < 58){
sb.append(c);
}
}
return sb.toString();
}
Test Code:
public static void main(final String[] args){
final String input = "0-123-abc-456-xyz-789";
final String result = stripNonDigits(input);
System.out.println(result);
}
Output:
0123456789
BTW: I did not use Character.isDigit(ch) because it accepts many other chars except 0 - 9.