Regex matches the start and end of a line in Java

I want to extract a specific string using Regex in Java. I currently have this template:

pattern = "^\\a.+\\sed$\n"; 

Suppose it matches a line starting with "a" and ending with "sed". This does not work. Did I miss something?

Deleted line \ n at the end of the pattern and replaced with "$": Still not working. Regular expression looks legal on my part.

What I want to extract is "sed" from the temp line.

 String temp = "afsgdhgd gfgshfdgadh a sed afdsgdhgdsfgdfagdfhh"; pattern = "(?s)^a.*sed$"; pr = Pattern.compile(pattern); math = pr.matcher(temp); 
+6
source share
2 answers

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 line
  • a - 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
+3
source

The temp line cannot match the pattern (?s)^a.*sed$ because this pattern says that the temp line should start with a and end the sequence sed , which is not the case. After the sequence "sed", your line has trailing characters. If you want to extract only part ... sed of the entire line, try using the unanchored "a. * Sed" pattern and use the find() method for the Matcher class :

 Pattern pattern = Pattern.compile("a.*sed"); Matcher m = pattern.matcher(temp); if (m.find()) { System.out.println("Found string "+m.group()); System.out.println("From "+m.start()+" to "+m.end()); } 
+1
source

All Articles