Search string for an occurance

How do I do this simple string searching, parsing, etc in Groovy???

theString="A whole lot of stuff with 1234567 in between.
len=7
posInString=theString.srchString("1234567")
newString=theString.mid(posInString,len)
log.debug "$newString"

result = 1234567

There are a few different ways it could be done.

Here’s one: http://stackoverflow.com/questions/25558031/how-to-find-all-matches-of-a-pattern-in-a-string-using-regex

1 Like

I kind of made my example a bit too simple. The string,in part look more like
"AuthorizationCode::someUnknownCode"
From this string I need to extract the code. Only known within this part string is “AuthorizationCode” and the length of “someUnknownCode”. The entire string may look something like
"In order to receive weather reports you must use the AuthorizationCode::someUnknownCode along with UserName and Passwords" So… I need to find the text “AuthorizationCode”, skip to the colon +1, extract the code.

Sounds like you just need to define the regex to get at it. I would suggest looking at the groovy docs for strings/regex, as well as stackoverflow. If you don’t have a local copy of groovy installed, you can use the online console here to test things out: https://groovyconsole.appspot.com/

1 Like

So… while waiting for the water for my pasta to boil, I played around with this a little.

Be forewarned, I’m terrible at regular expressions. I stand in awe of those who can whip up a RegEx to solve just about any problem (and I’ll always be terrified to modify any existing RegEx in a production codebase).

So at the risk of potentially spoiling any fun you may be having trying to do this, I came up with this. You can see the progression from naive to maybe just-clever-enough-to-be-dangerous. Links to the various stack overflow questions from which I learned stole are in included.

There are probably better ways to do this, and any regex gurus out there should take this as a challenge to do better :smile:

Edit - tl;dr:

def tester = "In order to receive weather reports you must use the AuthorizationCode::someUnknownCode along with UserName and Passwords"
def regEx = /(?<=AuthorizationCode::)\w+/
tester.findAll(regEx).each { println ("found code $it") }
3 Likes

Looks good… I’ll give it a try… :ok_hand: