Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regexp pattern Optional character

Tags:

regex

I want to match a string like 19740103-0379 or 197401030379, i.e the dash is optional. How do I accomplish this with regexp?

like image 369
user352985 Avatar asked Aug 20 '10 07:08

user352985


2 Answers

Usually you can just use -?. Alternatively, you can use -{0,1} but you should find that ? for "zero or one occurrences of" is supported just about everywhere.

pax> echo 19740103-0379 | egrep '19740103\-?0379'
19740103-0379

pax> echo 197401030379 | egrep '19740103\-?0379'
197401030379

If you want to accept 12 digits with any number of dashes in there anywhere, you might have to do something like:

-*([0-9]-*){12}

which is basically zero or more dashes followed by 12 occurrences of (a digit followed by zero or more dashes) and will capture all sorts of wonderful things like:

--3-53453---34-4534---

(of course, you should use \d instead of [0-9] if your regex engine has support for that).

like image 163
paxdiablo Avatar answered Oct 02 '22 03:10

paxdiablo


You could try different ones:

\d* matches a string consisting only of digits

\d*-\d* matches a string of format digits - dash - digits

[0-9\-]* matches a string consisting of only dashes and digits

You can combine them via | (or), so that you have for example (\d*)|(\d*-\d*): matches formats just digits and digits-dash-digits.

like image 38
phimuemue Avatar answered Oct 02 '22 01:10

phimuemue