lpd
lpd

Reputation: 2337

JS regular expression for repeated unique character

I am trying to determine whether a string contains exactly one given distinct character, repeated at least once. For example "bbbbb" should match but "ccMMcc" should not as it contains two different letters, c and m respectively. Presuming regular expressions would be the simplest way to do so, shame I suck at them, what will I need to match my string against?

Upvotes: 1

Views: 3298

Answers (3)

Alberto De Caro
Alberto De Caro

Reputation: 5213

The regex is:

\b(\w)\1*\b

that is:

  • \b: word boundary
  • (\w): the first char, group
  • \1*: any number of repetition of the first char

Upvotes: 2

core1024
core1024

Reputation: 1882

"tttt".match(/^(.)\1*$/) returns ["tttt","t"] but "test".match(/^(.)\1*$/) returns null

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838116

You can use a backreference:

^(.)\1+$

Upvotes: 9

Related Questions