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() +
"\'");
}
You could either use:
Or you could avoid regexes entirely:
You can report the region here using
indexandstring2.length()very easily. Of course if you want to be able to match regular expression patterns, you should use them.EDIT: As noted in another answer, both of these will remove
"dear"from"and_dear_Bob"leaving"and__Bob"– with the underscores representing spaces. So you’ll end up with two spaces between words. And it doesn’t force the match to be a whole word, either. It does exactly what you described, but it doesn’t give you the result you apparently want.Edit:
First choice of code outputs:
Hello c'Lint and dear Bobwhere Hello and c’Lint have two whitespace character in the middle.
While this code:
gets rid of additional whitespace character.