A similar but not the same string sequence

How to match the following sequence:

You wound DUMMY TARGET for 100 points of damage

but not:

You wound DUMMY TARGET with SKILL for 100 points of damage

with regex:

^You wound ([\\w\\s]+)(?!with) for (\\d+) points of damage

The regular expression above matches both lines, while I expect it to match only the first. Is there any way to make this work?

Sample Java code:

import java.util.regex.*;

public class Dummy {

 static Pattern pattern = Pattern.compile("^You wound ([\\w\\s]+)(?!with) for (\\d+) points of damage");
 static Matcher matcher = pattern.matcher("");
 static String FIRST_SEQUENCE =  "You wound DUMMY TARGET for 100 points of damage";
 static String SECOND_SEQUENCE =  "You wound DUMMY TARGET with SKILL for 100 points of damage";

 public static void main(String...args) {  
  if (matcher.reset(FIRST_SEQUENCE).matches())
   System.out.println("First match. Ok!");

  if (matcher.reset(SECOND_SEQUENCE).matches())
   System.out.println("Second match. Wrong!");
 }
}
+3
source share
3 answers

Try with the non-living operator + ?, ([\\w\\s]+?)

^You wound ([\\w\\s]+?)(?!with) for (\\d+) points of damage
+3
source

also, if the string to be matched is always uppercase, you can try:

^You wound ([A-Z\s]+) for (\d+) points of damage
0
source

:

"^ [A-Za-z0-9] [^ ] + [0-9] + "

0

Source: https://habr.com/ru/post/1726063/


All Articles