replace apostrophe ' in the middle of the word with \' in java

牧云@^-^@ 提交于 2019-12-11 02:31:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!