如何用Java中的“ XXXXX”替换字符串值?

问题描述 投票:1回答:3

我想用“ XXXX”替换特定的字符串值。问题是模式是非常动态的,在输入数据中不会有固定的模式。

我的输入数据

https://internetbanking.abc.co.uk/personal/logon/login/?userId=Templ3108&password=Got1&reme

我需要将用户ID和密码的值替换为“ XXXX”。

我的输出应该是-

https://internetbanking.abc.co.uk/personal/logon/login/?userId=XXXX&password=XXXX&reme

这是一个例子。在其他情况下,仅存在userId和密码-

userId = 12345678&password = stackoverflow&rememberID =

我正在Java中使用Regex来实现上述目的,但尚未成功。感谢任何指导。

[&]([^\\/?&;]{0,})(userId=|password=)=[^&;]+|((?<=\\/)|(?<=\\?)|(?<=;))([^\\/?&;]{0,})(userId=|password=)=[^&]+|(?<=\\?)(userId=|password=)=[^&]+|(userId=|password=)=[^&]+

PS:我不是Regex的专家。另外,请务必告诉我,除了Regex之外,是否还有其他替代方法可以实现此目的。

java regex string replace
3个回答
1
投票

这在两种情况下都可以解决(假设userId和密码仅包含一个单词字符[a-zA-Z_0-9],但可以进行改进以支持更多字符)

String input = "https://internetbanking.abc.co.uk/personal/logon/login/?userId=Templ3108&password=Got1&reme";

// Mask UserId
System.out.println(input.replaceAll("userId=(\\w+)", "userId=XXXXX"));

// Mask Password
System.out.println(input.replaceAll("password=(\\w+)", "password=XXXXX"));

您可以实现像这样的简单方法来屏蔽用户名和密码

String maskUserNameAndPassword(String input) {
    return input.replaceAll("userId=(\\w+)", "userId=XXXXX")
                .replaceAll("password=(\\w+)", "password=XXXXX");
}

0
投票

使用(?<=(\?|&))(userId | password)=(。*?)(?=(&| $))

  • (?<=(\?|&))确保前面带有?或&(但不是匹配项的一部分)
  • ((userId | password)=匹配userId或密码,然后=
  • ((。*?)匹配任何字符,只要不能执行下一条指令
  • ((?=(&| $))确保下一个字符为&或字符串的结尾,(但不属于匹配项)

然后,将其替换为$ 2 = xxxxx(以保留用户名或密码,然后选择replaceAll


0
投票

只需使用String类中的replace / replaceAll方法,它们支持Charset和regex。

String url = "https://internetbanking.abc.co.uk/personal/logon/login/?userId=Templ3108&password=Got1&reme";

url = url.replaceAll("(userId=.+?&)", "userId=XXXX&");
url = url.replaceAll("(password=.+?&)", "password=XXXX&");

System.out.println(url);

我也不是正则表达式专家,但是如果您发现它有用,我通常会使用此网站来测试我的表情并作为在线备忘单:

https://regexr.com

© www.soinside.com 2019 - 2024. All rights reserved.