Suppose, you were trying to look for something like ABC123
or ABC123.45
in your input String and you wanted to capture the letters and the numbers separately. You would use a regex (a bit similar to yours) like
([A-Z]+)([0-9]+(\.[0-9]+)?)
The above regex would match ABC123.45
and provide three groups as well that represent sub-parts of the whole match and are decided by where you put those ()
brackets. So, given our regex (without using ?:
) we got
Group 1 = ABC
Group 2 = 123.45
Group 3 = .45
Now, it may not make much sense to capture the decimal portion always and it actually has already been captured in our Group 2 as well. So, how would you make that group ()
non capturing? Yes, by using ?:
at the start as
([A-Z]+)([0-9]+(?:\.[0-9]+)?)
Now, you only get the two desired groups
Group 1 = ABC
Group 2 = 123.45
Notice, I also changed the last part of the regex from \.[0-9]*
to \.[0-9]+
. This would prevent a match on 123.
i.e. numbers without a decimal part but still having a dot.