Paul Fries Paul Fries - 1 month ago 16
Groovy Question

Groovy regex find and replace

I have a groovy value like the following:

"hostname blah blah blah"

When that occurs, I want to keep the hostname, but delete everything after it including the first space.

I'm having difficulty with the regex. Any ideas?
Thanks!

Answer

To extract the hostname and/or a part of a string by a regular expression can be done in a straightforward way.

If the values are separated by whitespace then can just split the string by a space character and use the first part. Split() method takes in a regular expression as its first argument.

String s = "hostname blah blah blah"
String[] parts = s.split(' ', 2)
if (parts) {
  println parts[0]
  s = parts[0] // if want to replace the variale s with just the hostname
}

Here is an alternate example using a regular expression to pull out the hostname part of the string value. The first part of the regular expression (\S+) is looking for a sequence of non-whitespace characters. For a set of possible hostnames, a stricter expression could be something like (\w+(\.\w+)*).

import java.util.regex.Matcher
if (s =~ /^(\S+)\s/) {
  println Matcher.lastMatcher.group(1)
}