Regex for a fixed-length string of character A followed by character B

I am trying to find a semi-regular regular expression for a string that is only 8 characters long. These 8 characters must consist of the following.

Another way to put this would be {n} b {8-n}, where n = 0 ... 8

String Matching Example: aaaaaaaa abbbbbbb aaaabbbb BBBBBBBBB

Inappropriate string example: bbbbaaaa aaaabaaa

+7
source share
2 answers

There are many ways to do this. Here is another alternative:

/^(?=a*b*$).{8}$/ 

Of course, you can switch to what it looks like:

 /^(?=.{8}$)a*b*$/ 
+3
source

You can use a positive lookahead to limit the length, and otherwise it's pretty simple.

 /^(?=[ab]{8}$)a{0,8}b{0,8}$/ 
+5
source

All Articles