Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex, Number or Empty

Tags:

regex

Can someone show me how to match 4 digits or nothing in Regex? I have been using RegexBuddy and so far i have come up with this but the help text is saying 'Or match regular expression number 2 below - the entire match attempt fails if this one fails to match' in regards to the pattern after the pipe.

I would like either of the two to provide a positive match.

^\d{4}|$
like image 212
Grant Avatar asked Sep 23 '13 10:09

Grant


People also ask

What is the range of regex numbers?

The Regex number range include matching 0 to 9, 1 to 9, 0 to 10, 1 to 10, 1 to 12, 1 to 16 and 1-31, 1-32, 0-99, 0-100, 1-100,1-127, 0-255, 0-999, 1-999, 1-1000 and 1-9999.

What is a regular expression in this syntax?

A very simple case of a regular expression in this syntax is to locate a word spelled two different ways in a text editor, the regular expression seriali[sz]e matches both "serialise" and "serialize".

Can a value be null in a regular expression?

If a value is required it cannot be null. The regular expression has nothing to do with it. Please Sign up or sign in to vote. The content must be between 30 and 50000 characters. … Download, Vote, Comment, Publish. Forgot your password? This email is in use. Do you need your password? Submit your solution! Read the question carefully.

How to avoid partial matching in regex?

Note that you don't want to allow partial matching, for example 123 abc, so you need the start and end anchors: ^...$. Your regex has a common mistake: ^\s*|\d+$, for example, does not enforce a whole match, as is it the same as (^\s*)| (\d+$), reading, Spaces at the start, or digits at the end.


3 Answers

Either 4 digits or nothing:

^(?:\d{4}|)$

This is closest to what you were trying to do.

I would go for the following for a slightly shorter one:

^(?:\d{4})?$

^\d{4}|$

That regex means either:

^\d{4} OR $

The first will match just any string that starts with 4 digits while the second will report a match on everything (it matches the end of a string, and since no character is specified, it will match the end of all strings).

When you're using a group, you're getting:

Either ^(?:\d{4})$ or ^(?:)$ (notice that the 'limits' of the OR operator changed), which is then equivalent to either ^\d{4}$ or ^$

like image 143
Jerry Avatar answered Oct 16 '22 12:10

Jerry


I think your approach is sound. You do need to keep operator precedence in mind though and use either

^(\d{4}|)$

or

^\d{4}$|^$
like image 22
NPE Avatar answered Oct 16 '22 13:10

NPE


I don't think if it needs OR

^(\d{4})?$
like image 26
revo Avatar answered Oct 16 '22 13:10

revo