Regex to replace specific characters before and after a specific substring

I am doing Java CodingBat exercises. Here is the one I just completed:

Given the string and non-empty string of the word, return the string consisting of each char immediately before and immediately after each occurrence of the word in the string. Ignore cases where char is not or after a word, and char can be turned on twice if it is between two words.

My code that 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 this is doable above with a regex expression, and if so, how?

+7
java string regex
source share
3 answers

You can use the Java regex Pattern and Matcher objects for 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)); } } 
+3
source share

To get a line containing a character before and after each occurrence of one line in another, you can use a regex expression:

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

and then you can iterate over the groups and combine them.

This expression will search (^|.) , Either the beginning of the string ^ , or any character . followed by str , followed by (.|$) , any character . or end of line $ .

You can 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; } 
+1
source share
 (?=(.|^)XY(.|$)) 

Try it. Just capture the captures and remove the None or empty values. Watch the demo.

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

+1
source share

All Articles