views:

49

answers:

1

I'm trying to update a stored NT account (Domain\user) with a new account. The new account comes as a String object.

I call my replaceAccount method to perform this, by running this line:

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

If the NT Account is "HOME\jdoe", and I then output the definition field of tempAcct, I see the NT login as "HOMEjdoe" instead.

By checking the replaceFirst method javadoc, the following can be read:

"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."

So, I've found that if instead of passing the NT account as it is ("HOME\jdoe") I pass "HOME"+Matcher.quoteReplacement("\\")+"jdoe", or "HOME\\\\jdoe", I then get correct results after using the replaceFirst method.

Is this the best method we can use or I'm totally misunderstanding how to use the Matcher.quoteReplacement() method?

+1  A: 

The argument of replaceFirst() is treated as an expression where $ and \ have a special meaning. If you want it to be treated as a literal string instead, you quote it with Matcher.quoteReplacement():

tempAcct.setDefinition(ExtractNTAccount.matcher(
    tempAcct.getDefinition()).replaceFirst(
         Matcher.quoteReplacement("nt=\"" + newNTLogin + "\""))); 
axtavt
Thanks. I actually just discovered this. I was using it at the incorrect level.
Dan