Java: How to remove the first substring match between two strings?

If I have two lines. let's say

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

and

string2="dear"

I want to compare strings and remove the first substring match. result of the above pairs of lines: i>

Hello c'Lint and dear Bob

This is the code I wrote that takes input and returns a matching match:

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() + 
            "\'");
}
+5
source share
1 answer

You can use:

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

Or you can completely avoid regular expressions:

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 indexand string2.length()very easily. Of course, if you want to be able to match regular expression patterns, you should use them.

EDIT: , "dear" "and_dear_Bob", "and__Bob" - , . , . . , , , , -, .

Edit: : Hello c'Lint and dear Bob Hello c'Lint . :

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

.

+17

All Articles