Reputation: 102
I know this has been asked a million times, but I can't get it to work. I'm filtering strings from a game's web API (http://pathofexile.com/api/public-stash-tabs -- Careful, ~5MB of data will retrieve from GET), trying to find which type of attribute I'm looking at, because I later need to replace it. (I'm looking at the "explicitMods" array within each of the Item objects, and identifying which type of modifier it is.)
My goal is to first identify which type of modifier I am dealing with, and then use String.replaceAll
to substitute the proper strings with ##
so that I can later replace ##
with actual values and search. I would be storing the values, or ranges, so that I can later identify what matches. String.replaceAll
not included here, because that bit works just fine.
This is my test class. All tests fail. I did test each pattern on regex101.com, to be sure but they only have javascript, php, python, and golang testers. Each method comment has a link to the test I made on 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();
}
}
Sample stacktrace (all are the same):
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)
Thank you in advance for your help,
Upvotes: 2
Views: 1385
Reputation: 44834
Use
".*(\\d+-\\d+).*(\\d+-\\d+).*"
Java
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());
Upvotes: 1