0

i'm trying to catch every two repeated characters in a word. I tried this:

(\w)\1+

but for some reason it only catches the first two pairs. For instance: the word "hellokitty", it catches the "ll" and ignores the other "tt" as tested in regex101

  • Note that your expression does *not* 'catch every two repeated characters' – it catches *as many as possible* repeated characters. For example, in `w000t` it matches `000`. To match *any* two repeated characters, use `(\w)\1`. To match *only* two characters, you need `(\w)\1(?!\1)` (well actually `(\w)(?<!\1\1)\1(?!\1)` but as it appears you are not allowed: "Subpattern references are not allowed within a look behind assertion" – see http://stackoverflow.com/questions/30678150/pcre-backreferences-not-allowed-in-lookbehinds for that). – Jongware Jun 07 '15 at 15:34
  • Thank you very much i didn't notice that – user3496557 Jun 08 '15 at 17:14

3 Answers3

1

You need to use modifier g for global matching :

/(\w)\1/g

https://regex101.com/r/nW7vS1/1

Mazdak
  • 105,000
  • 18
  • 159
  • 188
1

If you want to repeat a regex multiple times you have to use the global flag. On Regex101 that's just putting g in the box next to the regex.

How you have to use it in your code depends on the language you are using.

Javascript

/pattern/flags
new RegExp(pattern[, flags])

Example:

regex = /(\w)\1+/g;
regex = new RegExp("(\w)\1+", "g");

Python

re.compile(pattern, flags=0)

But python doesn't have the global flag. To find all occurences, use:

re.compile("(\w)\1+")
re.findall("Hellokitty")

This returns a tupple of matches.

Mathieu David
  • 4,706
  • 3
  • 18
  • 28
0

The g flag will make your regex global or repeating.

/(\w)\1+/g

Demo


If you want it to prevent it from getting triple repeating things, you can remove the +:

/(\w)\1/g

Demo

Downgoat
  • 13,771
  • 5
  • 46
  • 69