Verify if a word have a letter repeated in any position
I'd like know if there are a way to test if 开发者_如何学Goa 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.
/s{2,}/
or generally for any character:
/(.)\1/
/(\w)\1/
finds two alphanumeric characters next to each other
This will find and replace the duplicates:
s/(\w)\1/$1/
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.
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 :)
精彩评论