2017-05-31 329 views
0

我正在嘗試在Groovy腳本中進行模式匹配。我知道它是基於JAVA的。所以我嘗試在JAVA重新做類模式匹配。如何在Groovy Script中進行模式匹配?

我有兩個模式:

1)

String a = "$ for partA?" 
String b = "what is the $ for partA?" 

我想匹配B與由於爲b的子集。我試圖使用find(),但它返回我空...我認爲這可能是因爲$是一個特殊字符。

2)

String c = "the $ for partA is xx" 
String d = "I know the $ for partA is $5" 

我必須轉換成xx使用c.replace("xx", "\\d+(?:\\.\\d+)?|\\w+|\\W+");某種模式(因爲XX可以是任何東西)。但通過使用find(),它似乎不適用於$以及..

我該如何解決這兩個問題?

+0

入住這裏常規匹配 - http://mrhaki.blogspot.in/2009/09/groovy-goodness- matchers-for-regular.html和轉義'$' – Rao

回答

0

基於http://docs.groovy-lang.org/2.4.0/html/api/org/codehaus/groovy/runtime/StringGroovyMethods.htmlfind()將您的a視爲正則表達式。

在Java中,String有一個indexOf()方法,它只是簡單地在另一個字符串中找到第一個字符串。

對於你的第二個問題,它更復雜。在你的字符串中,你需要在正則表達式中轉義所有具有特殊含義的字符。我個人建議要麼寫a作爲一個正確的正則表達式,要麼使用indexOf來匹配它作爲一個正常的字符串,並分別處理結束部分。

+0

第二個問題,我試圖用c.quote()來轉義特殊字符,但它似乎逃避我的xx替代以及... –

+0

轉義它首先,然後做你的替代。 (雖然我仍然覺得它很脆弱......) –

+0

但它不工作,它似乎只匹配第一個字符串... –

0

在雙引號字符串的$具有特殊的意義,所以你要逃避它

但單引號字符是一個平常java

以下是正確的:

assert 'the $ in string' == "the \$ in string" 

案例1/

String a = '$ for partA?' 
String b = 'what is the $ for partA?' 
assert b.endsWith(a) 

String pattern = '^(what is the)?(.*) for partA\\?$' 
assert a.matches(pattern) 
assert b.matches(pattern) 

println a.replaceAll(pattern,'$2') // $ 
println b.replaceAll(pattern,'$2') // $ 

assert a.replaceAll(pattern,'$2') == b.replaceAll(pattern,'$2') 

情況下2/

不明白你想要什麼,但提取xx

String c = 'the $ for partA is xx' 
//$ in pattern means end of line so you need to escape it 
String v = c.replaceAll('^the \\$ for partA is (.*)$', '$1')