alanbuchanan
alanbuchanan

Reputation: 4173

Regex for replacing specific characters before and after specific substring

I am going through the Java CodingBat exercises. Here is the one I have just completed:

Given a string and a non-empty word string, return a string made of each char just before and just after every appearance of the word in the string. Ignore cases where there is no char before or after the word, and a char may be included twice if it is between two words.

My code, which works:

public String wordEnds(String str, String word){

    String s = "";
    String n = " " + str + " "; //To avoid OOB exceptions

    int sL = str.length();
    int wL = word.length();
    int nL = n.length();

    int i = 1;

    while (i < nL - 1) {

        if (n.substring(i, i + wL).equals(word)) {
            s += n.charAt(i - 1);
            s += n.charAt(i + wL);
            i += wL;
        } else {
            i++;
        }
    }

    s = s.replaceAll("\\s", "");

    return s;
}

My question is about regular expressions. I want to know if the above is doable with a regex statement, and if so, how?

Upvotes: 8

Views: 4072

Answers (3)

Moishe Lipsker
Moishe Lipsker

Reputation: 3034

To get a string containing the character before and after each occurrence of one string within the other, you could use the regex expression:

"(^|.)" + str + "(.|$)"

and then you could iterate through the groups and concatenate them.

This expression will look for (^|.), either the start of the string ^ or any character ., followed by str value, followed by (.|$), any character . or the end of the string $.

You could try something like this:

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

public String wordEnds(String str, String word){
    Pattern p = Pattern.compile("(.)" + str + "(.)");
    Matcher m = p.matcher(word);
    String result = "";
    int i = 0;
    while(m.find()) {
        result += m.group(i++);
    }
    return result;
}

Upvotes: 1

Narendra Yadala
Narendra Yadala

Reputation: 9664

You can use Java regex objects Pattern and Matcher for doing this.

public class CharBeforeAndAfterSubstring {
    public static String wordEnds(String str, String word) {
        java.util.regex.Pattern p = java.util.regex.Pattern.compile(word);
        java.util.regex.Matcher m = p.matcher(str);
        StringBuilder beforeAfter = new StringBuilder();

        for (int startIndex = 0; m.find(startIndex); startIndex = m.start() + 1) {
            if (m.start() - 1 > -1)
                beforeAfter.append(Character.toChars(str.codePointAt(m.start() - 1)));
            if (m.end() < str.length())
                beforeAfter.append(Character.toChars(str.codePointAt(m.end())));
        }

        return beforeAfter.toString();
    } 
    public static void main(String[] args) {
        String x = "abcXY1XYijk";
        String y = "XY";
        System.out.println(wordEnds(x, y));

    }
} 

Upvotes: 3

vks
vks

Reputation: 67968

(?=(.|^)XY(.|$))

Try this.Just grab the captures and remove the None or empty values.See demo.

https://regex101.com/r/sJ9gM7/73

Upvotes: 1

Related Questions