0

I have following promotion String in my application.

String promotion = "Watch on youtube: Mickey en de stomende drol! Watch on youtube.";

I want to replace the second word 'Youtube' by the hyperlink, so I tried:

promotion = promotion.replace("youtube","https://www.youtube.com/watch?v=a3leCIk2eyQ");

But this replaces the first youtube, and I want the second youtube to be replaced.

I also tried:

promotion = promotion.replaceAll("youtube","https://www.youtube.com/watch?v=a3leCIk2eyQ");

But this replaces both youtubes.

What is the best approach to replace the second occurance of "youtube" by the linK?

Jonas
  • 769
  • 1
  • 8
  • 37
  • http://stackoverflow.com/questions/3976616/how-to-find-nth-occurrence-of-character-in-a-string – Héctor Apr 08 '16 at 10:53
  • If it's always `youtube.` you could look for the dot. If it's aways the second `youtube` you could use a positive look-behind: `(?<=youtube.{0,999})youtube` (or if you don't want to add a maximum length of text in the look-behind use `(?<=youtube)(.*?)youtube` and re-add the group in the replacement by using the backreference `$1`.) – Thomas Apr 08 '16 at 10:53

1 Answers1

3

Since your second "youtube" string is also the last one, you can look for the last one and replace it.

    public static void main(String[] args)  {
        String promotion = "Watch on youtube: Mickey en de stomende drol! Watch on youtube.";
        System.out.println(promotion.replaceAll("(.*)(\\byoutube\\b)(.*)", "$1"+ "https://www.youtube.com/watch?v=a3leCIk2eyQ" + "$3" ));
    }

O/P :

Watch on youtube: Mickey en de stomende drol! Watch on https://www.youtube.com/watch?v=a3leCIk2eyQ.

If you want to replace only the second youtube in case you have multiple youtubes in your String, you can use :

public static void main(String[] args)  {
    String promotion = "Watch on youtube: Mickey en de stomende drol! Watch on youtube. asas youtube";
    String stringToReplace = "https://www.youtube.com/watch?v=a3leCIk2eyQ";
    System.out.println(promotion.replaceAll("(.*?\\byoutube\\b.*?)(\\byoutube\\b)(.*)", "$1"+  stringToReplace + "$3" ));
}

O/P :

Watch on youtube: Mickey en de stomende drol! Watch on https://www.youtube.com/watch?v=a3leCIk2eyQ. asas youtube

TheLostMind
  • 35,966
  • 12
  • 68
  • 104