Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Regex to find if I used the same character in multiple different locations?

Tags:

regex

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?

like image 307
Steven Rogers Avatar asked May 12 '17 20:05

Steven Rogers


2 Answers

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 delimiter

RegEx Demo

like image 144
anubhava Avatar answered Nov 15 '22 07:11

anubhava


You can use a back reference like this:

\d{3}([+.-])\d{3}\1\d{4}
  • The first operator that is matched [+-.] 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

like image 43
degant Avatar answered Nov 15 '22 06:11

degant