user2620053
user2620053

Reputation: 51

regular expression to match repeated characters?

I'm looking for a perl regular expression that will match strings made of only the same letters.

It should match aa, aaa, aaaa, aaaaa and so on, but not aabb, abba, aaab, aaaabaa and so on.

I know that I can use \1 to refer back to the first character like /(.)\1/, but that would also match aabb. Any advice?

Upvotes: 2

Views: 1212

Answers (1)

Jon Carter
Jon Carter

Reputation: 3436

This seems to work for me:

/^(.)\1*$/

The ^ character matches the beginning of the string, and the $ matches the end.

The whole expression can be translated into: "At the beginning of the string, match any character, followed by any number of that same character, followed by the end of the string.

Upvotes: 5

Related Questions