Mayday
Mayday

Reputation: 5146

regex or empty string not working

I am trying to validate an xml via an xsd. One of the fields its an optional field, which can contain value or not. In my case, the IP of a computer. I am checking with xsd the expression regular to check that it has IP format, but can't validate when it comes empty.

Here is the example

To validate IP I used following regex:

((([1-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([1-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]))|($)

As you see, I tried to use (the regex for the IP expression) | ($) But it does not work with empty string.

What am I doing wrong? How can I fix it? Thank you all

Upvotes: 2

Views: 249

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626961

There is a bug in your regex - the unescaped . matches any character. You can either escape it or put inside a character class, e.g. [.] so that it could only match a literal period (dot). To match an empty string, just add the ? quantifier at the end:

((([1-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}([1-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]))?
                                               ^^^ (dot inside a char class)                        ^ - The whole pattern can match 1 or 0 times

See the regex demo

To also match blank lines, you will need to add an alternative:

(\s*|((([1-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}([1-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])))
 ^^^^

See another regex demo

Upvotes: 1

Related Questions