1

I have a string like

a#?.text1

I have two other strings like c#1.text2 and d#2.text3

I want to replace #? in a#?.text1 with a#1.text1 if I choose c#1.text2. If I choose d#2.text3, then I want to replace a#?.text1 with a#2.text1. What is the easiest way to do this? I came up with a solution using groups, but my team doesn't think it is an efficient way of doing it. Here's my Java code:

Pattern strPattern = Pattern.compile("(\\w+)(#\\?)(\\.\\w+)");
Pattern replacePattern = Pattern.compile("(\\w+)(#\\d+)(\\.\\w+)");

Matcher strMatcher = strPattern.matcher("a#?.text1");
Matcher replaceMatcher1 = replacePattern.matcher("c#1.text2");
Matcher replaceMatcher2 = replacePattern.matcher("d#2.text3");

if(strMatcher.matches() && replaceMatcher1.matches()) {
  String number = replaceMatcher1.group(2);
  return strMatcher.replaceAll(strMatcher.group(1) + number + strMatcher.group(3));
} else if(strMatcher.matches() && replaceMatcher2.matches()) {
  String number = replaceMatcher2.group(2);
  return strMatcher.replaceAll(strMatcher.group(1) + number + strMatcher.group(3));
}

The feedback I got was that groups are inefficient and I have to find an easier way to do this.

Is there a better way to do this?

1 Answer 1

2

So looks like you just want to extract the number after # from your two strings which are c#1.text2 and d#2.text3 and replace ? just after # in a#?.text1 string.

The code you've written seems a little much where you're created two Pattern and then you're doing replacement using Matcher objects by capturing three groups, where as this can be easily done with some shorter codes without needing to create two Pattern object.

Just extract the number you need to replace and then replace it in the string directly using replaceFirst method on String object itself using these codes,

Pattern replacePattern = Pattern.compile("\\w+#(\\d+)\\.\\w+");
Matcher m = replacePattern.matcher("c#1.text2"); // same way for d#2.text3
if (m.matches()) {
    String digit = m.group(1); // the digit you wanted to extract
    String retVal = "a#?.text1".replaceFirst("(?<=#)\\?", digit); // replace ? preceded by # with the digit using replaceFirst
    System.out.println(retVal); // prints a#1.text1
    return retVal;
} else {
    System.out.println("String doesn't match the pattern");
}

Overall your codes can compactly be written as,

Pattern replacePattern = Pattern.compile("\\w+#(\\d+)\\.\\w+");
Matcher m = replacePattern.matcher("c#1.text2"); // same way for d#2.text3
if (m.matches()) {
    return "a#?.text1".replaceFirst("(?<=#)\\?", m.group(1)); // returns a#1.text1
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.