tags:

views:

59

answers:

3

Example

input: abc def abc abc pqr

I want to to replace abc at third position with xyz.

output: abc gef abc xyz pqr

Thanks in advance

A: 

One way to do this would be to use.

String[] mySplitStrings = null;
String.Split(" ");
mySplitString[3] = "xyz";

And then rejoin the string, its not the best way to do it but it works, you could put the whole process into a function like.

string ReplaceStringInstance(Seperator, Replacement)
{
  // Do Stuff
}
kyndigs
@kyndigs - the OP wants to replace the third match of a given pattern, not the fourth word in a sentence.
Andreas_D
+1  A: 

Group the three segments, that are the part before the replaced string, the replaced string and the rest and assemble the prefix, the replacement and the suffix:

String pattern = String.format("^(.*?%1$s.*?%1$s.*?)(%1$s)(.*)$", "abc");
String result = input.replaceAll(pattern, "$1xyz$3");

This solution assumes that the whole input is one line. If you have multiline input you'll have to replace the dots as they don't match line separators.

Andreas_D
Perhaps the following is more elegant: `s.replaceFirst("(abc.*abc.*)abc", "$1xyz")`
axtavt
Thanks alot............. I am so much thankful.
Its working fine for me.
+1  A: 

There's plenty of ways to do this, but here's one. It assumes that the groups of letters will be separated by spaces, and looks for the 3rd 'abc' block. It then does a single replace to replace that with 'xyz'.

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class main {
    private static String INPUT = "abc def abc abc pqr";
    private static String REGEX = "((?:abc\\ ).*?(?:abc\\ ).*?)(abc\\ )";
    private static String REPLACE = "$1xyz ";

    public static void main(String[] args) {
        System.out.println("Input: " + INPUT);
        Pattern p = Pattern.compile(REGEX);
        Matcher m = p.matcher(INPUT); // get a matcher object
        INPUT = m.replaceFirst(REPLACE);
        System.out.println("Output: " + INPUT);
    }
}
Jez
I love these type of questions with runnable code snippets. Post ideone links as well and you'll get tons of upvotes (at least from me :-) http://ideone.com/f8t2u
aioobe