tags:

views:

81

answers:

3

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 the regular expression:

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

The regular expression above is matching both strings while i expect to match only the first one. 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  A: 

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

^You wound ([\\w\\s]+?)(?!with) for (\\d+) points of damage
S.Mark
Thank you, but didn't work.
Fabiano Sobreira
I think you need 2 regex and match for second one first like this, `"You wound ([\\w\\s]+?) with \\w+ for (\\d+) points of damage"`, and if its match, skip it, else, match with `^You wound ([\\w\\s]+?) for (\\d+) points of damage`
S.Mark
The solution will work fine using conditionals. But i'm looking for a way to match this with a regular expression.
Fabiano Sobreira
A: 

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

^You wound ([A-Z\s]+) for (\d+) points of damage
chburd
The sequence can be anything from "Some dude" to "Dude" or "Some-Dude".
Fabiano Sobreira
A: 

Try this:

"^You wound [A-Za-z0-9 ][^with]+ for [0-9]+ points of damage"

worked for me

Mihir Mathuria