Java/Scala正则表达式:将括号中的数字移动到字符串外部

huangapple go评论64阅读模式
英文:

Java/Scala Regex: Move number in parentheses in string

问题

以下是翻译好的内容:

如何捕获数字(在下面的例子中为250)并将其插入替换字符串中?

我现有:"CHAR () FOR BIT DATA(250) NOT NULL"

我想要:"CHAR (250) FOR BIT DATA NOT NULL"

我希望在Scala中实现这一点,但我猜它只需使用java.util.regex

以下是我尝试过的:

val result = """"CHAR () FOR BIT DATA(250) NOT NULL""""
  .replaceAll("CHAR \\(\\) FOR BIT DATA\\(([0-9]+)\\)", "CHAR ($1) FOR BIT DATA")

我只是不知道如何获取仅数字,以便将它们重新插入新字符串中。

英文:

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

得分: 2

你可以使用

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

请参阅正则表达式演示

详细信息

  • (CHAR \() - 第1组 ($1): CHAR ( 文本
  • (\) FOR BIT DATA) - 第2组 ($2): ) FOR BIT DATA 文本
  • \( - 一个 ( 字符
  • (\d+) - 第3组 ($3): 一个或多个数字
  • \) - 一个 ) 字符。
英文:

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.

huangapple
  • 本文由 发表于 2020年9月24日 02:03:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/64033815.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定