8

If I have two strings .. say

string1="Hello dear c'Lint and dear Bob"

and

string2="dear"

I want to Compare the strings and delete the first occurrence of matching substring ..
the result of the above string pairs is:

Hello c'Lint and dear Bob

This is the code I have written which takes input and returns the matching occurence:

System.out.println("Enter your regex: ");
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));

String RegEx = bufferRead.readLine();
Pattern pattern = Pattern.compile(RegEx);
System.out.println("Enter input string to search: ");
bufferRead = new BufferedReader(new InputStreamReader(System.in));
Matcher matcher = pattern.matcher(bufferRead.readLine());

boolean found = false;
while (matcher.find()) {
    System.out.println("I found the text:\"" + matcher.group() +
            "\" starting at index \'" +
            matcher.start() + 
            "\' and ending at index \'" + 
            matcher.end() + 
            "\'");
}
4

1 に答える 1

20

You could either use:

string result = string1.replaceFirst(Pattern.quote(string2), "");

Or you could avoid regexes entirely:

int index = string1.indexOf(string2);
if (index == -1)
{
    // Not found. What do you want to do?
}
else
{
    String result = string1.substring(0, index) + 
                    string1.substring(index + string2.length());
}

You can report the region here using index and string2.length() very easily. Of course if you want to be able to match regular expression patterns, you should use them.

編集:別の回答で述べたように、これらは両方とも離れること"dear"から削除されます-アンダースコアはスペースを表します。したがって、単語の間に2つのスペースができてしまいます。また、一致が完全な単語になることも強制されません。それはあなたが説明したことを正確に行いますが、あなたが明らかに望む結果をあなたに与えません。"and_dear_Bob""and__Bob"

編集: コード出力の最初の選択:Hello c'Lint and dear Bob Helloとc'Lintの中央に2つの空白文字があります。このコードの間:

string result = string1.replaceFirst(Pattern.quote(string2+" "), ""));

追加の空白文字を取り除きます。

于 2013-01-26T08:34:58.640 に答える