2012-10-31 46 views
1

我有一個類似這樣的地圖。如何在常規圖中使用正則表達式

 xxx-10.name ='welcome' 
    xxx-10.age ='12' 
    xxx-10.std ='2nd' 

    xxx-12.name ='welcome' 
    xxx-12.age ='12' 
    xxx-12.std ='2nd' 

    yyy-10.name ='welcome' 
    yyy-10.age ='12' 
    yyy-10.std ='2nd' 

    yyy-12.name ='welcome' 
    yyy-12.age ='12' 
    yyy-12.std ='2nd' 

wen user給xxx我不得不返回包含所有xxx條目的子圖,而不管與它關聯的數量如何。有沒有辦法使用正則表達式來實現這一點?或者不用迭代鍵?

子圖中我能得到利用的工具..

回答

3

這應該做你想要什麼。

def fileContents = '''xxx-10.name ='welcome' 
        |xxx-10.age ='12' 
        |xxx-10.std ='2nd' 
        |xxx-12.name ='welcome' 
        |xxx-12.age ='12' 
        |xxx-12.std ='2nd' 
        |yyy-10.name ='welcome' 
        |yyy-10.age ='12' 
        |yyy-10.std ='2nd' 
        |yyy-12.name ='welcome' 
        |yyy-12.age ='12' 
        |yyy-12.std ='2nd'''.stripMargin() 

// Get a Reader for the String (this could be a File.withReader) 
Map map = new StringReader(fileContents).with { 
    // Create a new Properties object 
    new Properties().with { p -> 
    // Load the properties from the reader 
    load(it) 
    // Then for each name, inject into a map 
    propertyNames().collectEntries { 
     // Strip quotes off the values 
     [ (it): p[ it ][ 1..-2 ] ] 
    } 
    } 
} 

findByPrefix = { pref -> 
    map.findAll { k, v -> 
    k.startsWith(pref) 
    } 
} 

findByPrefix('xxx') 

手指交叉,你不要刪除這個問題;-)

+0

像烏拉圭回合最後一行;) – Jeevi

4

有在常規集合過濾功能。見API

def result = [a:1, b:2, c:4, d:5].findAll { it.value % 2 == 0 } 
assert result.every { it instanceof Map.Entry } 
assert result*.key == ["b", "c"] 
assert result*.value == [2, 4] 

在你的情況下,使用String.startsWith()yourSearchString搜索時:

map.findAll { it.key.startsWith(yourSearchString) } 
+1

最好使用'startsWith'因爲這是他的興趣,因爲我在做的[我10分鐘前的答案](http://stackoverflow.com/a/13156735/6509) –

+1

感謝您的提示。我編輯了這篇文章。 – mana

相關問題