Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Similar but not same string sequence

Tags:

java

regex

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!");
 }
}
like image 597
Fabiano Sobreira Avatar asked Mar 07 '26 23:03

Fabiano Sobreira


1 Answers

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

^You wound ([\\w\\s]+?)(?!with) for (\\d+) points of damage
like image 56
YOU Avatar answered Mar 10 '26 12:03

YOU



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!