-6

我正在使用 Java。我想检查 URL 中的正则表达式是否包含数字 id 等路径变量并将其替换为*.

我尝试了不同的模式,例如\/\d+.*,但没有得到我期望的结果。

input url: https://stackoverflow.com/questions/ask/123/456
expected output: https://stackoverflow.com/questions/ask/*/*

另一个:

input url: https://stackoverflow.com/questions/ask/123/456/find
expected output: https://stackoverflow.com/questions/ask/*/*/find

用“/*”替换“/”的正确正则表达式是什么?

4

1 回答 1

2

匹配全为数字的路径段的正则表达式:

/\d+(?=/|$)

用星号替换所有:

String masked = url.replaceAll("/\\d+(?=/|$)", "/*");

现场演示

分解正则表达式:

  • /\\d+是斜线后跟数字
  • (?=/|$)表示匹配必须后跟斜杠输入结尾 ( $)

替换将匹配的斜线加上一个星号。

于 2021-08-29T23:42:30.073 回答