I need to validate input: valid variants are either number or empty string. What is the correspondent regular expression?
String pattern = "\d+|<what shoudl be here?>";
UPD: dont suggest "\d*" please, I'm just curious how to tell "empty string" in regexp.
ε, the empty string, is a regular expression.
To check if a String matches a Pattern one should perform the following steps: Compile a String regular expression to a Pattern, using compile(String regex) API method of Pattern. Use matcher(CharSequence input) API method of Pattern to create a Matcher that will match the given String input against this pattern.
The most portable regex would be ^[ \t\n]*$ to match an empty string (note that you would need to replace \t and \n with tab and newline accordingly) and [^ \n\t] to match a non-whitespace string. Save this answer.
In this particular case, ^\d*$
would work, but generally speaking, to match pattern
or an empty string, you can use:
^$|pattern
^
and $
are the beginning and end of the string anchors respectively.|
is used to denote alternates, e.g. this|that
.In the so-called multiline mode (Pattern.MULTILINE/(?m)
in Java), the ^
and $
match the beginning and end of the line instead. The anchors for the beginning and end of the string are now \A
and \Z
respectively.
If you're in multiline mode, then the empty string is matched by \A\Z
instead. ^$
would match an empty line within the string.
Here are some examples to illustrate the above points:
String numbers = "012345";
System.out.println(numbers.replaceAll(".", "<$0>"));
// <0><1><2><3><4><5>
System.out.println(numbers.replaceAll("^.", "<$0>"));
// <0>12345
System.out.println(numbers.replaceAll(".$", "<$0>"));
// 01234<5>
numbers = "012\n345\n678";
System.out.println(numbers.replaceAll("^.", "<$0>"));
// <0>12
// 345
// 678
System.out.println(numbers.replaceAll("(?m)^.", "<$0>"));
// <0>12
// <3>45
// <6>78
System.out.println(numbers.replaceAll("(?m).\\Z", "<$0>"));
// 012
// 345
// 67<8>
matches
In Java, matches
attempts to match a pattern against the entire string.
This is true for String.matches
, Pattern.matches
and Matcher.matches
.
This means that sometimes, anchors can be omitted for Java matches
when they're otherwise necessary for other flavors and/or other Java regex methods.
String.matches()
/^\d*$/
Matches 0 or more digits with nothing before or after.
Explanation:
The '^' means start of line. '$' means end of line. '*' matches 0 or more occurences. So the pattern matches an entire line with 0 or more digits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With