java - 用于替换特定子字符串前后特定字符的正则表达式

标签 java regex string

我正在完成 Java CodingBat 练习。 Here是我刚刚完成的:

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.

我的代码,有效:

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

我的问题是关于正则表达式的。我想知道上面的内容是否可以用正则表达式语句来实现,如果可以,怎么做?

最佳答案

您可以使用 Java 正则表达式对象 PatternMatcher 来执行此操作。

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

    }
} 

关于java - 用于替换特定子字符串前后特定字符的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29528066/

相关文章:

javascript - 正则表达式javascript搜索单词但忽略几个单词

java - 正则表达式替换java中的特定字符

java - 手机号码的正则表达式

c - 基于 char * (string) 而不是单个 char 的 strtok

java - Android 中的自动登录

java - 用java写一个递归方法

java - 字符串作为 boolean 值

java - 分割字符串、搜索和翻译子字符串 JAVA

java - Android - 定时 UI 事件(带有暂停/恢复)

java - java中InputStream和InputStreamReader的区别