Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

java - codingBat plusOut using regex

This is similar to my previous efforts (wordEnds and repeatEnd): as a mental exercise, I want to solve this toy problem using regex only.

Description from codingbat.com:

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"

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.

So let's see what the stackoverflow community comes up with.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This passes all their tests:

public String plusOut(String str, String word) {
  return str.replaceAll(
    String.format("(?<!(?=\Q%s\E).{0,%d}).", word, word.length()-1),
    "+"
  );  
}

Also, I get:

plusOut("1xAxAx2", "xAx") → "+xAxAx+"

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...