I need to extract from text possible credit card numbers. I have regex for different types of credit cards from http://www.richardsramblings.com/regex/credit-card-numbers/. But if the match preceded or followed by any digit, it is not considered as a valid credit card number, but just as unrelated number.
I’ve tried to add non-capturing group (?:\D|) before and after expected card regex,e.g
It mostly works OK, but if 2 credit cards are next to each other, separated by single character:
the first card matched, but the second is not found.
Fortunately I found an answer http://stackoverflow.com/questions/3926451/how-to-match-but-not-capture-part-of-a-regex, that gave me a reference to use look-around assertions:
Negative lookahead is indispensable if you want to match something not followed by something else.
So I was able to search what I need using negative look-arounds: negative lookbehind (?<!\d) before the expression and negative lookahead (?!\d) after the expression
See my example of regex in https://regex101.com/r/iY2aR6/8
I want to clarify that the purpose of non-capturing groups is different to look-arounds .
In regex, normal parentheses not only group parts of a pattern, they also capture the sub-match to a capture group. At other times, you do not need the overhead.
If you need parentheses to work in natural way to only group parts of a pattern, you need to specify non-capturing group by putting ?: after opening parenthesis