使用groovy

时间:2017-03-07 01:25:42

标签: groovy

使用groovy如何从包含括号的文件中获取单词/文本。

示例:

  

乔治(程序员)过去常常想。

要获得的字词:a programmer

1 个答案:

答案 0 :(得分:0)

这里有一个解决问题的示例程序:

String inp = 'George (a programmer) used to think much.'
def matcher = inp =~ /\(([^\)]+)\)/   // Try to find a match
if (matcher) {    // Something found
  String str = matcher[0][1]     // Get the 1st capture group
  printf("Found: %s.\n", str)
  def words = str.tokenize()     // Create a list of words
  words.eachWithIndex{ it, i -> printf("%d: %s.\n", i, it)}
} else {
  print("Not found")
}

注意正则表达式中括号的含义:

  • 外部(反斜杠引用)括号是 literal 括号(我们是 寻找这些字符)。
  • 不带引号的括号(它们之间)是捕获组的分隔符
  • 它们之间的剩余(引用)右括号是char 应该出现在捕获组中。