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
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).
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).
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.
*b$' will match all strings ending with a 'b'.
You can use a positive lookahead to limit the length, and otherwise, it's fairly simple.
/^(?=[ab]{8}$)a{0,8}b{0,8}$/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With