現在、正規表現を使用して、codingbat.com の問題を解決しようとしています。
私はこれが初めてなので、段階的な説明をいただければ幸いです。これは String メソッドで比較的簡単に解決できましたが、正規表現を使用しようとしています。
プロンプトは次のとおりです。文字列と空でない単語文字列を指定すると、文字列内の単語が出現する直前と直後の各 char で構成される文字列を返します。単語の前後に char がない場合は無視してください。2 つの単語の間にある場合は、char が 2 回含まれている可能性があります。
wordEnds("abcXY123XYijk", "XY") → "c13i"
wordEnds("XY123XY", "XY") → "13"
wordEnds("XY1XY", "XY") → "11"
等
これまでの私のコード:
String regex = ".?" + word+ ".?";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
String newStr = "";
while(m.find())
newStr += m.group().replace(word, "");
return newStr;
問題は、単語の複数のインスタンスが連続して存在する場合、m.find() が単語を超えて進行するため、プログラムが単語の前の文字を見逃すことです。
例:wordEnds("abc1xyz1i1j", "1")
を返す必要"cxziij"
がありますが、私のメソッドは を返します"cxzij"
。"i"
他の一般的な正規表現の問題に適用できる説明を含む、面倒ではない解決策をいただければ幸いです。