首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >正则表达式匹配,Java。匹配和提取

正则表达式匹配,Java。匹配和提取
EN

Stack Overflow用户
提问于 2017-02-21 09:52:43
回答 2查看 799关注 0票数 2

我知道这已经被问了一百万次了,但是我不能让它工作。我正在从游戏的web中过滤字符串(http://pathofexile.com/api/public-stash-tabs --小心,大约5MB的数据将从GET中检索到),试图找出我正在查看的属性类型,因为我稍后需要替换它。(我正在查看每个Item对象中的"explicitMods“数组,并确定它是哪种类型的修饰符。)

我的目标是首先确定我正在处理哪种类型的修饰符,然后使用String.replaceAll将适当的字符串替换为##,这样以后我就可以用实际的值替换##并进行搜索。我将存储值或范围,以便以后可以识别匹配的值。这里没有包含String.replaceAll,因为它工作得很好。

这是我的测试类。所有测试都失败。我确实在regex101.com上测试了每种模式,但它们只有javascript、php、python和golang测试器。每个方法注释都有一个指向我在regex101上进行的测试的链接。

代码语言:javascript
复制
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();
  }
}

示例堆栈跟踪(都是一样的):

代码语言:javascript
复制
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)

提前感谢你的帮助,

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-02-21 10:04:00

使用

代码语言:javascript
复制
".*(\\d+-\\d+).*(\\d+-\\d+).*"

Java

代码语言:javascript
复制
String regex = ".*(\\d+-\\d+).*(\\d+-\\d+).*";
String text = "Adds (4-5) to (8-9) Physical Damage";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);

System.out.println(matcher.matches());
票数 1
EN

Stack Overflow用户

发布于 2017-02-21 10:05:23

您应该删除开始位置和结束位置的/

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42357319

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档