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.
In this particular case,
^\d*$would work, but generally speaking, to matchpatternor an empty string, you can use:Explanation
^and$are the beginning and end of the string anchors respectively.|is used to denote alternates, e.g.this|that.References
Related questions
Note on multiline mode
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\Aand\Zrespectively.If you’re in multiline mode, then the empty string is matched by
\A\Zinstead.^$would match an empty line within the string.Examples
Here are some examples to illustrate the above points:
Note on Java
matchesIn Java,
matchesattempts to match a pattern against the entire string.This is true for
String.matches,Pattern.matchesandMatcher.matches.This means that sometimes, anchors can be omitted for Java
matcheswhen they’re otherwise necessary for other flavors and/or other Java regex methods.Related questions
String.matches()