使用正则表达式的codingBat plusOut [英] codingBat plusOut using regex
问题描述
这与我之前的工作类似( wordEnds
和 repeatEnd
):作为一项心理锻炼,我想解决这个问题仅使用正则表达式的玩具问题.
This is similar to my previous efforts (wordEnds
and repeatEnd
): as a mental exercise, I want to solve this toy problem using regex only.
给出一个字符串和一个非空的单词字符串,返回原始字符串的版本,其中所有字符都被加号(
"+"
)代替,除了单词字符串的外观保留不变.
Given a string and a non-empty word string, return a version of the original string where all chars have been replaced by pluses (
"+"
), except for appearances of the word string which are preserved unchanged.
plusOut("12xy34", "xy") → "++xy++"
plusOut("12xy34", "1") → "1+++++"
plusOut("12xy34xyabcxy", "xy") → "++xy++xy+++xy"
没有提及是否允许重叠(例如,什么是 plusOut("+ xAxAx +","xAx")
?),但是我的非正则表达式解决方案无法处理重叠和它通过了,所以我想如果它使 word
变得更简单,我们可以假设它不重叠(如果您提供两种变体的解决方案,都可以加分!).
There is no mention whether or not to allow overlap (e.g. what is plusOut("+xAxAx+", "xAx")
?), but my non-regex solution doesn't handle overlap and it passes, so I guess we can assume non-overlapping occurrences of word
if it makes it simpler (bonus points if you provide solutions for both variants!).
无论如何,我都想使用正则表达式来解决这个问题(与以前在其他两个问题上一样).我什至没有任何可显示的东西,因为我什么都没用.
In any case, I'd like to solve this using regex (of the same style that I did before with the other two problems), but I'm absolutely stumped. I don't even have anything to show, because I have nothing that works.
因此,让我们看看stackoverflow社区带来了什么.
So let's see what the stackoverflow community comes up with.
推荐答案
这通过了所有测试:
public String plusOut(String str, String word) {
return str.replaceAll(
String.format("(?<!(?=\\Q%s\\E).{0,%d}).", word, word.length()-1),
"+"
);
}
我也得到:
plusOut("1xAxAx2", "xAx") → "+xAxAx+"
如果这是您想要的结果,那么我也通过了重叠测试,但是我不得不承认,这是偶然的.:D
If that's the result you were looking for then I pass your overlap test as well, but I have to admit, that one's by accident. :D
这篇关于使用正则表达式的codingBat plusOut的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!