I am trying to create a regular expression that will allow up to 50 characters for a name plus up to 8 additional characters for a version number. I have a regular expression that is doing that exactly, except for the scenario that someone were to remove the space between the name and version number. Here is the regex:
^([\w\W]{3,50})(\s\(v[\d]{1,4}\)){0,1}?$
It properly matches this for example:
acvbg yuleacvbg yuleacvbg yuleacvbg yuleacvbg yule (v9999)
but, if I remove the space between the appended version number, I no longer have a match
acvbg yuleacvbg yuleacvbg yuleacvbg yuleacvbg yule(v9999)
How do I get both of these examples to work?
You can make the space itself optional:
^([\w\W]{3,50})(\s?\(v[\d]{1,4}\)){0,1}?$
^
Which allows 0 or 1 space. To allow an arbitrary number of spaces (including none), you can use the * quantifier
^([\w\W]{3,50})(\s*\(v[\d]{1,4}\)){0,1}?$
^
Also, [\w\W] means "a word character or a non-word character", which matches any character. So [\w\W] can be replaced with ..
Lastly, the {0,1} at the end of the expression can simply be omitted, since the optionality of the version number is already being expressed by ?.
Therefore, the expression can be simplified to:
^(.{3,50})(\s*\(v[\d]{1,4}\))?$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With