2

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.

vaibhavcool20
  • 861
  • 3
  • 11
  • 28
  • Try [`property.replaceAll("\\b'\\b", "\\\\'");`](https://ideone.com/ZhM9KH). Or if you really mean between letters, `.replaceAll("(?<=\\p{L})'(?=\\p{L})", "\\\\'")` – Wiktor Stribiżew Jun 23 '17 at 17:07
  • worked, answer the question and I will accept and upvote. do you know where I can learn this stuff? – vaibhavcool20 Jun 23 '17 at 17:12
  • Just so you're aware: the input isn't valid XPath, and the desired output isn't valid XPath either. If you want this as a valid XPath expression in a Java string literal, then for XPath 1.0 you want `//*[@text=\"ab'cd\"]`, while for XPath 2.0 an alternative would be `//*[@text='ab''cd']` – Michael Kay Jun 23 '17 at 17:48
  • @MichaelKay how should automate this //*[@text=''80s']. '80s is the text. – vaibhavcool20 Jul 01 '17 at 15:11
  • If that's XPath-1.0-embedded-in-Java, use `"//*[@text=\"'80s\"]"` – Michael Kay Jul 01 '17 at 16:30
  • i tried this //*[@text=\"'80s\"] it doesn't work in selenium. – vaibhavcool20 Jul 01 '17 at 16:48

1 Answers1

3

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})", "\\\\'"));
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563