user3496557
user3496557

Reputation: 11

Regex: with repeated characters

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

Upvotes: 0

Views: 209

Answers (3)

Mathieu David
Mathieu David

Reputation: 5278

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.

Upvotes: 1

Downgoat
Downgoat

Reputation: 14361

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

Upvotes: 0

Kasravnd
Kasravnd

Reputation: 107287

You need to use modifier g for global matching :

/(\w)\1/g

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

Upvotes: 1

Related Questions