UPDATE
You want to combine a sed , so you can use a\\s+sed if there are only spaces between a and sed :
String s = "afsgdhgd gfgshfdgadh a sed afdsgdhgdsfgdfagdfhh"; Pattern pattern = Pattern.compile("a\\s+sed"); Matcher matcher = pattern.matcher(s); while (matcher.find()){ System.out.println(matcher.group(0)); }
Watch the IDEONE demo
Now , if there can be anything between a and sed , use a moderate greedy token:
Pattern pattern = Pattern.compile("(?s)a(?:(?!a|sed).)*sed"); ^^^^^^^^^^^^^
Watch another demo of IDEONE .
ORIGINAL RESPONSE
The main problem with your regex is \n at the end. $ is the end of the line, and you are trying to match another character after the end of the line, which is impossible. Also, \\s matches the space character, but you need the literal s .
You need to remove \\ and \n and do . match a newline, and also advisbale use the * quantifier to allow 0 characters between them:
pattern = "(?s)^a.*sed$";
See regex demo
The regular expression matches:
^ - start of linea - letter a.* - 0 or more of any characters (since the modifier (?s) makes the character . Any character, including a new line)sed - the literal sequence of letters sed$ - end of line
source share