英文:
Java Regex to replace only part of string (url)
问题
我想要替换字符串中的数字部分。在大多数情况下,它要么是完整的URL或URL的一部分,但也可能只是一个普通字符串。
/users/12345
变为/users/XXXXX
/users/234567/summary
变为/users/XXXXXX/summary
/api/v1/summary/5678
变为/api/v1/summary/XXXX
http://example.com/api/v1/summary/5678/single
变为http://example.com/api/v1/summary/XXXX/single
注意,我不会替换 /api/v1
中的 1
。
到目前为止,我只有以下这些代码似乎在大多数情况下都能工作:
input.replaceAll("/[\\d]+$", "/XXXXX").replaceAll("/[\\d]+/", "/XXXXX/");
但这有两个问题:
- 替换后的长度与原字符串长度不匹配。
- 替换的字符是硬编码的。
有没有更好的方法来做这个?
英文:
I want to replace only numeric section of a string. Most of the cases it's either full URL or part of URL, but it can be just a normal string as well.
/users/12345
becomes/users/XXXXX
/users/234567/summary
becomes/users/XXXXXX/summary
/api/v1/summary/5678
becomes/api/v1/summary/XXXX
http://example.com/api/v1/summary/5678/single
becomeshttp://example.com/api/v1/summary/XXXX/single
Notice that I am not replacing 1
from /api/v1
So far, I have only following which seem to work in most of the cases:
input.replaceAll("/[\\d]+$", "/XXXXX").replaceAll("/[\\d]+/", "/XXXXX/");
But this has 2 problems:
- The replacement size doesn't match with the original string length.
- The replacement character is hardcoded.
Is there a better way to do this?
答案1
得分: 3
在Java中,您可以使用:
str = str.replaceAll("(/|(?!^)\\G)\\d(?=\\d*(?:/|$))", "$1X");
[RegEx演示][1]
[1]: https://regex101.com/r/G2C9Ma/4
**正则表达式详细信息:**
- `\G`断言匹配的位置在前一个匹配的末尾,或者在字符串的开头(对于第一个匹配)。
- `(/|(?!^)\\G)`: 在捕获组#1中匹配`/`或前一个匹配的末尾(但不在开头)。
- `\\d`: 匹配一个数字。
- `(?=\\d*(?:/|$))`: 确保数字后面跟着`/`或结束。
- **替换:** `$1X`:用捕获组#1后面跟着`X`来替换。
英文:
In Java you can use:
str = str.replaceAll("(/|(?!^)\\G)\\d(?=\\d*(?:/|$))", "$1X");
RegEx Details:
\G
asserts position at the end of the previous match or the start of the string for the first match.(/|(?!^)\\G)
: Match/
or end of the previous match (but not at start) in capture group #1\\d
: Match a digit(?=\\d*(?:/|$))
: Ensure that digits are followed by a/
or end.- Replacement:
$1X
: replace it with capture group #1 followed byX
答案2
得分: 0
不是一个 Java
程序员,但是这个想法应该是可以转移的。只需捕获 /
,数字和可选的 /
,计算第二组的长度,然后再放回去。
所以
(/)(\d+)(/?)
变成
$1XYZ$3
参见regex101.com 上的演示和这个答案,其中包含了一个类似于 Python
或 PHP
的 lambda 等效方法。
英文:
Not a Java
guy here but the idea should be transferrable. Just capture a /
, digits and /
optionally, count the length of the second group and but it back again.
So
(/)(\d+)(/?)
becomes
$1XYZ$3
See a demo on regex101.com and this answer for a lambda equivalent to e.g. Python
or PHP
.
答案3
得分: 0
首先,您需要类似于以下内容的代码:
String new_s1 = s3.replaceAll("(\\/)(\\d)+(\\/)?", "$1XXXXX$3");
英文:
First of all you need something like this :
String new_s1 = s3.replaceAll("(\\/)(\\d)+(\\/)?", "$1XXXXX$3");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论