问题
I have an XPath
//*[@title='ab'cd']
and I want to output it as
//*[@title='ab\'cd']
I am using this code
property = property.replaceAll("^[a-zA-Z]+(?:'[a-zA-Z]+)*", "\'");
but it is outputting
//*[@text='ab'cd']
I couldn't find a similar question on StackOverflow.if there is please post the link in the comments.
回答1:
To replace a '
in between two letters you need a (?<=\p{L})'(?=\p{L})
regex.
A (?<=\p{L})
is a positive lookbehind that requires a letter immediately to the left of the current location, and (?=\p{L})
is a positive lookahead that requires a letter immediately to the right of the current location.
The replacement argument should be "\\\\'"
, 4 backslashes are necessary to replace with a single backslash.
See the Java demo:
String s= "//*[@title='ab'cd']";
System.out.println(s.replaceAll("(?<=\\p{L})'(?=\\p{L})", "\\\\'"));
来源:https://stackoverflow.com/questions/44726427/replace-apostrophe-in-the-middle-of-the-word-with-in-java