Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

I'm trying to find a halfway decent regex for a string exactly 8 characters long. Those 8 characters should be comprised of a's followed by b's.

Another way of putting this would be a{n}b{8-n} where n=0...8

Example Matching Strings: aaaaaaaa abbbbbbb aaaabbbb bbbbbbbb

Example Non-Matching Strings: bbbbaaaa aaaabaaa

like image 345
AmishDave Avatar asked Jan 30 '13 20:01

AmishDave


People also ask

What does \+ mean in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What does \b mean in regex?

The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).

How do you restrict length in regex?

By combining the interval quantifier with the surrounding start- and end-of-string anchors, the regex will fail to match if the subject text's length falls outside the desired range.

What regex gives all strings ending with B?

*b$' will match all strings ending with a 'b'.


1 Answers

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

/^(?=[ab]{8}$)a{0,8}b{0,8}$/
like image 69
FThompson Avatar answered Oct 06 '22 00:10

FThompson