w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Regex failing to match number and dash with letter (or space and letter)

It's because of the parentheses.

I've looked everywhere in the documentation and found an interesting sentence on this page:

[...] if the pattern contains any parentheses, the portion of the text that matched the first parenthesized subexpression (the one whose left parenthesis comes first) is returned.

I took your first expression:

([0-9]+)-?([:space:])?([A-Za-z])?

and wrapped it in parentheses:

(([0-9]+)-?([:space:])?([A-Za-z])?)

and it works fine (see SQLFiddle).

Update:

Also, because you're looking for - or space, you could rewrite your middle expression to [-|s]? (thanks Matthew for pointing that out), which leads to the following possible REGEX:

(([0-9]+)[-|s]?([A-Za-z])?)

(SQLFiddle)

Update 2:

While my answer provides the explanation as to why the result represented a partial match of your expression, the expression I presented above fails your third test case.

You should use the regex provided by Matthew in his answer.





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.