英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论