Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for a string made only of repeated chars

I need to create a validation that determines if a string is only made of repeated chars. So, for example it would catch "pp" but not "happy".

So far, I can check for the repeating char using this:

/(.)\1+/.test(value);

How can I change this regex to only catch "pp" and not catch "happy"? Would regex be the best way to do this?

like image 266
Nora Avatar asked Mar 14 '23 08:03

Nora


2 Answers

Your regex is almost valid, you only have to add ^ and $ respectively at the beginning and at the end, to ensure that the string doesn't contain any other characters:

/^(.)\1+$/.test(value);

See also a Regex101 demo.

like image 180
Michał Perłakowski Avatar answered Mar 30 '23 07:03

Michał Perłakowski


An inverse should also work.. ie, this regex should match a string which contain two non repeated characters or empty string. Negation ! exists before the regex should do an inverse match.

> !/(.)(?!\1).|^$/.test('happy')
false
> !/(.)(?!\1).|^$/.test('')
false
> !/(.)(?!\1).|^$/.test('pp')
true
> !/(.)(?!\1).|^$/.test('ppo')
false
> !/(.)(?!\1).|^$/.test('ppppppppp')
true
> 

DEMO

like image 37
Avinash Raj Avatar answered Mar 30 '23 08:03

Avinash Raj