vaibhavcool20
vaibhavcool20

Reputation: 871

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

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.

Upvotes: 2

Views: 1426

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627103

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})", "\\\\'"));

Upvotes: 3

Related Questions