从文本中读取特定字符串

时间:2021-07-28 08:55:34

标签: groovy

以下是正文:


请求:删除用户

帐号:n34567

感谢与问候

骡子


我正在尝试检索字符串 AccountId:n34567

错误: 错误:java.lang.IndexOutOfBoundsException:索引超出范围 0..-1(索引 = 0)

代码:

String adjusted = text.toString().replaceAll("^(?:[\t ]*(?:\r?\n|\r))+", " ");
System.out.println("******* New Formated Email Bodu ***** :"+adjusted)
String content = (adjusted =~ "AccountId:[0-9]+")[0]
System.out.println("Content :"+content)

2 个答案:

答案 0 :(得分:1)

假设您的输入文本位于这样的变量中:

def text = '''request: user removal

AccountId:n34567

Thanks & Regards

Mule'''

然后你就可以这样做了

def acct = text.find(~/AccountId:(\S+)/)

\S 匹配任何非空白字符

答案 1 :(得分:0)

def text = '''request: user removal

AccountId:n34567

Thanks & Regards

Mule'''

def accountIdLine = text.lines().find {it.startsWith('AccountId:')}
if (accountIdLine) {
    def accountId = accountIdLine - 'AccountId:'
    println "the Account ID is $accountId"
} else {
    println 'No Account ID was found'
}

打印:

the Account ID is n34567