我知道这已被问了一百万次,但我无法让它工作。 我从游戏的web API中筛选字符串(http://pathofexile.com/api/public-stash-tabs - 小心,大约5MB的数据将从GET中检索),尝试查找我正在查看的属性类型,因为我稍后需要替换它。 (我正在查看每个Item对象中的“explicitMods”数组,并确定它是哪种类型的修饰符)。正则表达式匹配,Java。匹配和提取
我的目标是首先确定我正在处理的修饰符的类型,然后使用String.replaceAll
用##
替换适当的字符串,这样我可以稍后用实际值和搜索替换##
。我将存储值或范围,以便稍后可以确定匹配的内容。这里不包括String.replaceAll
,因为这个位工作得很好。
这是我的测试班。所有测试都失败。我确实测试了regex101.com上的每个模式,但是他们只有javascript,php,python和golang测试人员。每个方法评论都有一个链接,指向我在regex101上进行的测试。
package arbitrary.package.name;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.assertTrue;
public class RegexTests {
private static Logger log = LoggerFactory.getLogger(RegexTests.class);
@Test
public void testIntegers() {
// https://regex101.com/r/PVfYGX/1
assertTrue(compileAndMatch("/.*(.\\d+).+(.\\d+).*/", "Adds 80 to 115 Physical Damage"));
}
@Test
public void testIntegersWithRanges() {
// https://regex101.com/r/u3UQqM/1
assertTrue(compileAndMatch("/.*(\\d+-\\d+).*(\\d+-\\d+).*/", "Adds (4-5) to (8-9) Physical Damage"));
}
@Test
public void testDecimals() {
// https://regex101.com/r/CpaV1y/1
assertTrue(compileAndMatch("/.*(\\d+.?\\d+).*/", "0.2% of Elemental Damage Leeched as Life"));
}
private boolean compileAndMatch(String regex, String text) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
log.info("{} {} \"{}\"", regex, matcher.matches() ? "matches" : "does not match", text);
return pattern.matcher(text).matches();
}
}
样品堆栈跟踪(所有的都一样):
2017-02-20 20:35:44.876 [main] INFO arbitrary.package.name.RegexTests - /.*(\d+.?\d+).*(\d+.?\d+).*/ does not match "Adds (4-5) to (8-9) Physical Damage"
java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:86)
at org.junit.Assert.assertTrue(Assert.java:41)
at org.junit.Assert.assertTrue(Assert.java:52)
at arbitrary.package.name.RegexTests.testIntegersWithRanges(RegexTests.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
预先感谢您的帮助,
非常感谢。 JavaScript漏入Java的愚蠢错误。 – Qbert