1

I was trying case insensitive pattern matching. For the sake of learning i tried the following and finding it difficult to analyze what is happening.

   String x = "Hello";
   String pattern = "(?i)";
   System.out.println(x.replaceAll(pattern, "</code>")); 

Output is

</code>H</code>e</code>l</code>l</code>o</code>

Can someone please explain this behaviour

Rohit Sharma
  • 13,787
  • 8
  • 57
  • 72

2 Answers2

3

Using (?i) bare is equivalent to matching case-insensitive empty String

You need to have something after (?i) to apply case-insensitivity matching to..

That is why this pattern matches every empty string, after each character, and also before the first character, and replaces it with : - </code>

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • >matches every empty string, after each character... It is printing in the beginning as well. And where does empty string exist ?. There is nothing . And How a nothing is getting replaced by something ? – Rohit Sharma Oct 14 '12 at 15:37
  • @Javanator Try using `"a".contains("");` -> It will return true. Becaues every string contains at least one empty string.. – Rohit Jain Oct 14 '12 at 15:39
  • Yes agree to that but question is where are these empty strings are coming from. "Hello" has only five character. And i feel to occupy memory accordingly for five characters only. nothing else – Rohit Sharma Oct 14 '12 at 15:41
  • are there any java doc or other links for these magical creatures :). That proves your statement that a empty substring to be associated with a string. – Rohit Sharma Oct 14 '12 at 15:44
  • how can a thing that holds 0 space is getting matched and is getting replaced by something – Rohit Sharma Oct 14 '12 at 15:50
  • @Javanator. See this post: - http://stackoverflow.com/a/145516/1679863 A Jon-Skeet answer will clear all your doubt.. – Rohit Jain Oct 14 '12 at 15:50
  • @Javanator I hope I made you clear? You can also See this answer: - http://stackoverflow.com/a/263257/1679863 – Rohit Jain Oct 14 '12 at 15:55
  • Yes Rohit. Infact you did it extensively . Thanks +1 and accept too – Rohit Sharma Oct 14 '12 at 16:00
1

That pattern matches nothing, and there is one nothing to either side of each character :)

(Well, there are a lot of nothings, actually, but there can only be one match per index.)

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • 1
    i thought the same that it is replacing nothing as i didn't provided anything after (?i). But does Nothing Exist ? Confused to think :) – Rohit Sharma Oct 14 '12 at 15:32