2017-02-21 112 views
2

我知道這已被問了一百萬次,但我無法讓它工作。 我從遊戲的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) 

預先感謝您的幫助,

回答

1

使用

".*(\\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()); 
+0

非常感謝。 JavaScript漏入Java的愚蠢錯誤。 – Qbert

0

您應該刪除開始和結束位置的/

+0

感謝Kerwin,這是正確的。我在另一個人的回答中寫下了答案,因爲他在你面前回答。 – Qbert