gpt4 book ai didi

java - 用包含反斜杠 (\) 的字符串替换字符串的最佳方法

转载 作者:行者123 更新时间:2023-11-30 09:54:08 25 4
gpt4 key购买 nike

我正在尝试使用新帐户更新存储的 NT 帐户(域\用户)。新帐户以字符串对象的形式出现。

我通过运行以下行调用我的 replaceAccount 方法来执行此操作:

tempAcct.setDefinition(ExtractNTAccount.matcher(tempAcct.getDefinition()).replaceFirst("nt=\""+newNTLogin+"\""));

如果 NT 帐户是“HOME\jdoe”,然后我输出 tempAcct 的定义字段,我看到的 NT 登录名是“HOMEjdoe”。

通过查看replaceFirst方法的javadoc,可以看到如下内容:

"Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceFirst(java.lang.String). Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired."

因此,我发现如果不是按原样传递 NT 帐户 ("HOME\jdoe"),而是传递 "HOME"+Matcher.quoteReplacement("\\")+"jdoe""HOME\\\\jdoe",然后我在使用 replaceFirst 方法后得到正确的结果。

这是我们可以使用的最佳方法还是我完全误解了如何使用 Matcher.quoteReplacement() 方法?

最佳答案

replaceFirst() 的参数被视为一个表达式,其中 $\ 具有特殊含义。如果您希望它被视为文字字符串,您可以使用 Matcher.quoteReplacement() 将其引用:

tempAcct.setDefinition(ExtractNTAccount.matcher(
tempAcct.getDefinition()).replaceFirst(
Matcher.quoteReplacement("nt=\"" + newNTLogin + "\"")));

关于java - 用包含反斜杠 (\) 的字符串替换字符串的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3504711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com