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.


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())
| improve this answer | |
  • 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 – Ralph Callaway Feb 13 '18 at 19:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.