如何匹配以下序列:
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!");
}
}
答案 0 :(得分:3)
尝试使用非贪婪的算子+? ,([\\w\\s]+?)
^You wound ([\\w\\s]+?)(?!with) for (\\d+) points of damage
答案 1 :(得分:0)
另外,如果要匹配的字符串总是大写,您可以尝试:
^You wound ([A-Z\s]+) for (\d+) points of damage
答案 2 :(得分:0)
试试这个:
“^你伤[A-Za-z0-9] [^ with] + [0-9] +伤害点”
为我工作