Java/Regular Expressions/Digit Number
Содержание
Check if given string is a number (digits only)
public class Main {
public static boolean isNumber(String string) {
return string.matches("^\\d+$");
}
public static void main(String[] args) {
System.out.println(isNumber("123"));
}
}
Check if given string is number with dot separator and two decimals
public class Main {
public static boolean isNumberWith2Decimals(String string) {
return string.matches("^\\d+\\.\\d{2}$");
}
public static void main(String[] args) {
sysout isNumberWith2Decimals("1234.123")
}
}
Check if given string is numeric (-+0..9(.)0...9)
public class Main {
public static boolean isNumeric(String string) {
return string.matches("^[-+]?\\d+(\\.\\d+)?$");
}
public static void main(String[] args) {
sysout isNumeric("123.123")
}
}
Match a single digit
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
// match a single digit
Pattern p = Pattern.rupile("\\d");
Matcher matcher = p.matcher("5");
boolean isOk = matcher.matches();
System.out.println("original pattern matches " + isOk);
// recycle the pattern
String tmp = p.pattern();
Pattern p2 = Pattern.rupile(tmp);
matcher = p.matcher("5");
isOk = matcher.matches();
System.out.println("second pattern matches " + isOk);
}
}
Matcher Pattern number
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
Pattern p = Pattern.rupile("\\d");
Matcher m1 = p.matcher("55");
Matcher m2 = p.matcher("fdshfdgdfh");
System.out.println(m1.pattern() == m2.pattern());
// return true
}
}
Match number
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] argv) throws Exception {
Pattern number = Pattern.rupile("\\G\\d+\\.?\\d*");
Matcher mat = number.matcher("this is a test 999");
System.out.println(mat.find());
}
}
//false