Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for replacing specific characters before and after specific substring

Tags:

java

string

regex

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?

like image 958
alanbuchanan Avatar asked Apr 09 '15 01:04

alanbuchanan


3 Answers

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

    }
} 
like image 143
Narendra Yadala Avatar answered Nov 15 '22 16:11

Narendra Yadala


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

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

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

like image 30
vks Avatar answered Nov 15 '22 17:11

vks


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;
}
like image 21
Moishe Lipsker Avatar answered Nov 15 '22 16:11

Moishe Lipsker