如何匹配以下顺序:
You wound DUMMY TARGET for 100 points of damage
但不是:
You wound DUMMY TARGET with SKILL for 100 points of damage
使用正则表达式:
^You wound ([\\w\\s]+)(?!with) for (\\d+) points of damage
上面的正则表达式匹配两个字符串,而我希望仅匹配第一个。有什么办法可以使这项工作吗?
示例Java代码:
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!");
}
}
最佳答案
尝试使用非贪婪运算符+吗? ,([\\w\\s]+?)
^You wound ([\\w\\s]+?)(?!with) for (\\d+) points of damage