I am using regex to find line which starts with 'aaaa'

pattern myPattern = pattern.compile('^(aaaa)\b.*');
String a = 'aaaa,777,ttttt,rrrrrr';
a += '\n' + 'tttttt,ttttt,0000';
matcher myMatcher = myPattern.matcher(a);


System.debug(myMatcher.group()); this line is throwing exception no group is found. I have tested my regex at website https://www.freeformatter.com/java-regex-tester.html

Can any one tell me what i am doing wrong here.

1 Answer 1


You have to call myMatcher.find(). Calling matches just tells you if the expression matches the whole input. Also note that you need to escape your special characters (\\b) and you probably want to search only up to the end of the line ($). That will only work if you set the multi-line flag, otherwise $ means end of string.

Matcher m = Pattern.compile('(?m)^aaaa\\b.*$')
if (m.find())
  • and for a second I thought we had a platform bug, totally thought System.assert(pattern.matches('^.*$','aaaa\nbbbb')); should pass, makes complete sense if it's matches is the whole string. Great explanation Feb 13, 2018 at 19:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .