Roman Roman - 1 month ago 7
Java Question

What is the pattern for empty string?

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.

Answer

In this particular case, ^\d*$ would work, but generally speaking, to match pattern or an empty string, you can use:

^$|pattern

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 \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.


Examples

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>

Note on Java 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.

Related questions

Comments