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());
Answer from vikingsteve on Stack OverflowTry
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
try this
str.matches(".*\\d.*");
If you want to extract the first number out of the input string, you can do-
public static String extractNumber(final String str) {
if(str == null || str.isEmpty()) return "";
StringBuilder sb = new StringBuilder();
boolean found = false;
for(char c : str.toCharArray()){
if(Character.isDigit(c)){
sb.append(c);
found = true;
} else if(found){
// If we already found a digit before and this char is not a digit, stop looping
break;
}
}
return sb.toString();
}
Examples:
For input "123abc", the method above will return 123.
For "abc1000def", 1000.
For "555abc45", 555.
For "abc", will return an empty string.
You could use Pattern instead, I think "matches" method looks for the whole string to match the regular expression.
Try the next code:
int combinations = 0;
String pass = "!!AAabas1";
if (Pattern.compile("[0-9]").matcher(pass).find()) {
combinations = combinations + 10;
}
if (Pattern.compile("[a-z]").matcher(pass).find()) {
combinations = combinations + 26;
}
if (Pattern.compile("[A-Z]").matcher(pass).find()) {
combinations = combinations + 26;
}
Here's my attempt. Note, this uses unicode categories for validation so is non-latin language friendly.
import java.util.regex.Pattern;
public class PasswordValidator {
public static void main(String[] args) {
final PasswordValidator passwordValidator = new PasswordValidator();
for (String password : new String[] { "abc", "abc123", "ABC123", "abc123ABC", "!!!AAabas1", "гшщз",
"гшщзЧСМИ22" }) {
System.out.printf("Password '%s' is %s%n", password, passwordValidator.isValidPassword(password) ? "ok"
: "INVALID");
}
}
private static final Pattern LOWER_CASE = Pattern.compile("\\p{Lu}");
private static final Pattern UPPER_CASE = Pattern.compile("\\p{Ll}");
private static final Pattern DECIMAL_DIGIT = Pattern.compile("\\p{Nd}");
/**
* Determine if a password is valid.
*
* <p>
* A password is considered valid if it contains:
* <ul>
* <li>At least one lower-case letter</li>
* <li>At least one upper-case letter</li>
* <li>At least one digit</li>
* </p>
*
* @param password
* password to validate
* @return True if the password is considered valid, otherwise false
*/
public boolean isValidPassword(final String password) {
return containsDigit(password) && containsLowerCase(password) && containsUpperCase(password);
}
private boolean containsDigit(final String str) {
return DECIMAL_DIGIT.matcher(str).find();
}
private boolean containsUpperCase(final String str) {
return UPPER_CASE.matcher(str).find();
}
private boolean containsLowerCase(final String str) {
return LOWER_CASE.matcher(str).find();
}
}
Here's the output:
Password 'abc' is INVALID
Password 'abc123' is INVALID
Password 'ABC123' is INVALID
Password 'abc123ABC' is ok
Password '!!!AAabas1' is ok
Password 'гшщз' is INVALID
Password 'гшщзЧСМИ22' is ok
You can replace each number by a new line + the number:
String multiline = s.replaceAll("(\\d+)", "\n$1");
(\\d+)captures the number$1refers to the captured number
Replace any instance of one or more digits with the system line separator followed by the matched digit(s).
As such:
String s = "S.No.DistrictMarketPrice 1 Agra Achhnera NIL 2 Agra Agra NIL 3 Agra Fatehabad NIL 4 Agra Fatehpur Sikri NIL 5 Agra Jagner NIL 6 Agra Jarar NIL 7 Agra Khairagarh NIL 8 Agra Shamshabad NIL 9 Aligarh Atrauli NIL 10 Aligarh Chharra NIL";
System.out.println(
s.replaceAll("\\d+", System.getProperty("line.separator") + "$0")
);
Output
S.No.DistrictMarketPrice
1 Agra Achhnera NIL
2 Agra Agra NIL
3 Agra Fatehabad NIL
4 Agra Fatehpur Sikri NIL
5 Agra Jagner NIL
6 Agra Jarar NIL
7 Agra Khairagarh NIL
8 Agra Shamshabad NIL
9 Aligarh Atrauli NIL
10 Aligarh Chharra NIL
There is one major flaw that will come back and haunt you with this code. If you enter an invalid number, there is absolutely no indication whatsoever that it was invalid.
If it is not valid, you should do this:
throw new IllegalArgumentException("Invalid mobile number: " + mobile);
Incorporating Heslacher's suggestions I would do this:
public void setMobile(String mobile) {
if (!containsOnlyDigits(mobile)) {
throw new IllegalArgumentException("Invalid mobile number: " + mobile);
}
this.mobile = mobile;
}
Another edge case that should be handled is the empty string. I assume you don't want to classify that as a valid mobile number? Then handle it also in containsOnlyDigits or handle it in setMobile.
if (mobile.isEmpty()) {
throw new IllegalArgumentException("Empty string is not a valid mobile number");
}
You should extract the validation, meaning the checking if the string only contains digits, to a separate method like so
private static boolean containsOnlyDigits(final String value) {
for (int i = 0; i < value.length(); i++) {
if(!Character.isDigit(value.charAt(i))) {
return false;
}
}
return true;
}
and use it in the setMobile() method like so
public void setMobile(String mobile) {
if(containsOnlyDigits(mobile)) {
this.mobile = mobile;
}
}
So each method is doing only one thing.
Because the method setMobile() is public you should check if the passed mobile is not null.
Disclaimer: Written in the editor without testing.
Firstly, you should call Matcher.find() before you invoke Matcher.group()
use "\\d+" as regex if you consider 127 as a whole single digit.
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(s);
while(m.find()){
System.out.println(m.group() + " " + m.start() + " " + m.end());
}
If you really want to find single digits, you need this:
Pattern pattern = Pattern.compile("\\d");
Matcher matcher = pattern.matcher(testline);
while (matcher.find()) {
System.out.println(matcher.group());
}
if you want to find non-floating-point numbers, change the regex to "\\d+".