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'

ユーザーが xxx を指定すると、関連する番号に関係なく、すべての xxx エントリを含むサブマップを返す必要があります。正規表現を使用してこれを達成する方法はありますか? またはキーを反復せずに?

SubMap ユーティリティを使用して取得できます。

4

2 に答える 2

5

groovy にはコレクション用のフィルター機能があります。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) }
于 2012-10-31T11:31:20.817 に答える
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' )

指が交差したあなたはこの質問を削除しないでください;-)

于 2012-10-31T11:21:31.387 に答える