Victoria Serkov
Victoria Serkov

Reputation: 43

Java regex to groovy

I got this code in java which replaces with white space the regex:

private static final String SCRUB_REGEX = "[\\<\\>\\\"\\'\\(\\)\\\\\\n\\r\\f]";
private static final String SCRUB_REPLACEMENT = " ";
String trim = value.replaceAll(SCRUB_REGEX, SCRUB_REPLACEMENT).trim();

I am trying to use this in a groovy script of SoapUI and it doesn't seem to actually trim. Does groovy not recognize the java regex?

temp =testStep.getPropertyValue(sorted).replaceAll("[\\<\\>\\\"\\'\\(\\)\\\\\\n\\r\\f]", " ").trim()

I have done import to import java.util.regex.*

Upvotes: 1

Views: 352

Answers (2)

tim_yates
tim_yates

Reputation: 171164

You don't need to import java.util.regex.*

Slash strings make things easier:

String SCRUB_REGEX = /[<>"'()\\\n\r\f]/
String SCRUB_REPLACEMENT = ' '
String trim = value.replaceAll(SCRUB_REGEX, SCRUB_REPLACEMENT).trim();

So this will replace all of:

  • <
  • >
  • "
  • '
  • (
  • )
  • \
  • \n
  • \r
  • \f

With a space

Upvotes: 2

Mena
Mena

Reputation: 48434

Hard to tell without input and output, but a few comments:

  1. You don't need to escape special characters when inside a character class (enclosed between square brackets []). You still need to use a single escape for special constructs. You can use the following pattern instead:

"[<>\"'()\n\r\f]"

  1. You might want to replace multiple occurrences of your characters with only one whitespace. In which case, add a quantifier, as such:

"[<>\"'()\n\r\f]+"

  1. String.trim only trims your given String's beginning and end off whitespace. Anything in the middle will not be trimmed. If the String is entirely whitespace, then trim will return an empty String.

Upvotes: 0

Related Questions