So I am looking through different numbers that have different delimiters, and I want to find all numbers that have the same delimiter.
Basically, I want the following
123+456+7890 // MATCH
123-456-7890 // MATCH
123.456.7890 // MATCH
123+456-7890 // FAILURE
My current regex I plan to use was
\d{3}[+-.]\d{3}[+-.]\d{4}
However, it would match number sequences that have the different delimiters. I don't want to use one big huge OR for something like this because the real life equivalent has many more characters that could fit there.
Is there a way to match the same character in multiple locations?
You can use a captured group and a back-reference to ensure same delimiter is used again.
^\d{3}([+.-])\d{3}\1\d{4}$
([+.-])
here we capture delimiter in group #1\1
Here we are using back-reference of same delimiterRegEx Demo
You can use a back reference like this:
\d{3}([+.-])\d{3}\1\d{4}
[+-.]
is kept inside a capturing group so that it can be referenced later.\1
is a backreference to the first capturing group which in this case is [+-.]
so it will ensure that the operator is same as the previous one.Regex 101 Demo
You can read more about backreferences here
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