GodFather
GodFather

Reputation: 3146

Verify if a word have a letter repeated in any position

I'd like know if there are a way to test if a word have a letter repeated in any position?

I'm currently using this regex to test it, but not work, becouse if I add more then 2 's' the test returns true.

  /s{0,2}/.test('süuaãpérbrôséê'); //expected true
  /s{0,2}/.test('ssüuaãpérbrôéê'); //expected true
  /s{0,2}/.test('süuaãpérbrôéê'); //expected true
  /s{0,2}/.test('süuaãpérbrôséês'); //expected fail

Thanks.

Upvotes: 1

Views: 175

Answers (4)

kizu
kizu

Reputation: 43224

using lookahead you can achieve something like that:

^(?=.*(\w)(.*\1){1}.*$)((?!\1).)*\1(((?!\1).)*\1){1}((?!\1).)*$

Where {1} is number of repeatings minus 1, so for finding if there are three repeations this would look like:

^(?=.*(\w)(.*\1){2}.*$)((?!\1).)*\1(((?!\1).)*\1){2}((?!\1).)*$

And for two or three:

^(?=.*(\w)(.*\1){1,2}.*$)((?!\1).)*\1(((?!\1).)*\1){1,2}((?!\1).)*$

etc.

The lookaheads with backreferences can be very powerful :)

Upvotes: 0

GodFather
GodFather

Reputation: 3146

The only way that I found to resolve this problem is using php preg_match_all, on this way I can count how much times the character repeat.

  $s = 'süuaãpérbrôséê';
  preg_match_all('/s/i', $s, $m);
  echo count($m[0]); //outputs 2 

My initial idea was pass a regex and use preg_match to verify the match exists in a determined number of times, but I think that it's not possible, so I'll create a method that receive the word and the regex that I need match and it will return the number of matches.

Thanks.

Upvotes: 0

Karoly Horvath
Karoly Horvath

Reputation: 96258

/s{2,}/

or generally for any character:

/(.)\1/

Upvotes: 2

kevlar1818
kevlar1818

Reputation: 3125

/(\w)\1/ finds two alphanumeric characters next to each other

This will find and replace the duplicates: s/(\w)\1/$1/

Upvotes: 0

Related Questions