Gopi Meesala
Gopi Meesala

Reputation: 3

Read a particular string from a text

Below is the text:


request: user removal

AccountId:n34567

Thanks & Regards

Mule


I am trying to retrieve the string AccountId:n34567

Error: Error: java.lang.IndexOutOfBoundsException: index is out of range 0..-1 (index = 0)

code:

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)

Upvotes: 0

Views: 307

Answers (2)

Renato
Renato

Reputation: 13690

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'
}

Prints:

the Account ID is n34567

Upvotes: 0

tim_yates
tim_yates

Reputation: 171074

Assuming your input text is in a variable like so:

def text = '''request: user removal

AccountId:n34567

Thanks & Regards

Mule'''

Then you can just do this

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

\S matches any non-whitespace character

Upvotes: 1

Related Questions