简体   繁体   中英

I need a regular expression to replace 3rd matching substring

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

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
}

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.

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM