如何在Groovy中使用正则表达式提取短操作系统名称?

时间:2019-05-22 17:31:08

标签: regex groovy

我正在尝试从以下输入字符串获取输出“ Windows Server 2008”:“远程工作站中的操作系统是Microsoft Windows Server 2008 R2 Enterprise”

但是我只能得到:“ Windows Server”而不是“ 2008”

我在www.regex101.com上尝试过,我相信我有正确的正则表达式

def sentence = "The operating system in the remote workstation is Microsoft Windows Server 2008 R2 Enterprise"

def regexWinWorkstation = "Microsoft (Windows [a-zA-Z0-9]+)"
def regexWinServer = "Microsoft (Windows Server [a-zA-Z0-9]+)"

def result = sentence.find(regexWinWorkstation) {
    println it[1]
}

if (!result) {
    result = sentence.find(regexWinServer){
    println it[1]}
}

预期输出:“ Windows Server 2008” 实际输出:“ Windows Server”

1 个答案:

答案 0 :(得分:1)

def sentences = [
  "The operating system in the remote workstation is Microsoft Windows Server 2008 R2 Enterprise",
  "The operating system is Microsoft Windows 10 Professional",
  "The operating system is Windows XP"
]
def regexWinOptionalServer = /(?<=Microsoft )?Windows (Server )?[a-zA-Z0-9]+/

sentences.each{
  println it.find(regexWinOptionalServer)
}

打印

Windows Server 2008
Windows 10
Windows XP