Java/Scala Regex: Move number in parentheses in string

Viewed 51

How can I capture the number (250 in the following case) and insert it in the replacement string?

What I have: "CHAR () FOR BIT DATA(250) NOT NULL"

What I want: "CHAR (250) FOR BIT DATA NOT NULL"

I'm looking to do this in Scala, but I guess it simply uses java.util.regex.

Here's what I've tried:

"""CHAR () FOR BIT DATA(250) NOT NULL""".replaceAll("CHAR \\(\\) FOR BIT DATA\\(([0-9]+)\\)", "Here is the string: $0")

I simply don't know how to get only the digits to re-insert them in a new string.

1 Answers

You can use

.replaceAll("""(CHAR \()(\) FOR BIT DATA)\((\d+)\)""", "$1$3$2")

See the regex demo

Details

  • (CHAR \() - Group 1 ($1): CHAR ( text
  • (\) FOR BIT DATA) - Group 2 ($2): ) FOR BIT DATA text
  • \( - a ( char
  • (\d+) - Group 3 ($3): one or more digits
  • \) - a ) char.
Related