Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for identical characters despite line breaks and spaces?

How can I create a regular expression in python that matches consecutive identical characters, regardless of whether line breaks or spaces are in between? The number of identical characters should be adjustable.

examples (e can be any character except newline or space):

match: eee, e e e, e e e

no match: ebe, e b e, e e

attempts:

(\S)[\s\n]*\1{2}
(\S)(?:\s|\n)*\1{2} 
like image 773
Rex Avatar asked Dec 14 '25 07:12

Rex


1 Answers

You may use this regex:

\A\s*(\S)(?:\s*\1\s*)+\Z

RegEx Demo

RegEx Details:

  • \A: asserts position at start of the string
  • \s*: Match 0 or more whitespaces
  • (\S): Match any non-whitespace character and capture in group #1
  • (?:\s*\1\s*)+: Match same value we captured in group #1 surrounded with 0 or more whitespaces on either side. Repeat this group 1 or more times
  • \Z: asserts position at the end of the string
like image 93
anubhava Avatar answered Dec 16 '25 20:12

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!