2009-12-18 69 views
3

如何匹配以下顺序:相似但不相同的字符串序列

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

”with SKILL“总是固定的? – YOU 2009-12-18 14:51:32

+0

单词“with”始终是固定的。技能可以是一个或多个间隔的单词。 这些是真正的序列示例: “你伤害了Ongbúrz狂战士68点古代矮人造成的伤害。” “你用Valar的Anthem伤害了Ongbúrz狂战士,造成了215点古代矮人造成的伤害。” – 2009-12-18 17:34:03

回答

3

尝试用非贪婪操作符+? ,([\\w\\s]+?)

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

谢谢,但没有奏效。 – 2009-12-18 14:48:42

+1

我认为你需要2个正则表达式并且像这样匹配第二个'''你伤害(\\ w \\ s)+?)(\\ d +)点伤害“,并且if它的匹配,跳过它,否则,与'^你伤害([\\ w \\ s] +?)与(\\ d +)点伤害相匹配 – YOU 2009-12-18 14:58:34

+0

该解决方案将使用条件正常工作。但我正在寻找一种方法将其与正则表达式匹配。 – 2009-12-18 17:37:16

0

而且,如果要匹配的字符串总是大写,你可以尝试:

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

序列可以是“某些人”到“兄弟”或“某人”的任何内容。 – 2009-12-18 14:50:00

0

试试这个:

“^你伤口[A-ZA-Z0 -9] [^ with] + for [0-9] +点伤害“

为我工作