gpt4 book ai didi

java - 相似但不相同的字符串序列

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:04:29 25 4
gpt4 key购买 nike

如何匹配如下序列:

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

关于java - 相似但不相同的字符串序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1928558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com