gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:27:30 24 4
gpt4 key购买 nike

我正在完成 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com