0

i have a problem with the following java code i am not getting the desired output can you please help.

import java.util.regex.*; public class Main { public static void main(String[] args) { String word = "novel"; String nestedWord = "nonnonovnovnovelelelvelovelvel"; Pattern p = Pattern.compile(word); Matcher m = p.matcher(nestedWord); while(m.find()){ nestedWord = nestedWord.replaceFirst(word,""); } System.out.println(nestedWord); } } // it should print "novel" but i am getting "nonnonovnovnovelelelvelovelvel"

1st Aug 2020, 3:57 PM
Prabh Singh
Prabh Singh - avatar
2 Respuestas
+ 2
You are getting right output ,while loop runs once since novel is found only one time in whole string and therefore nestedWord.replaceFirst replaces first and only occurence of novel and returns=> nonnonovnovelelvelovelvel
1st Aug 2020, 4:13 PM
Abhay
Abhay - avatar
0
System.out.println( m.find() ? word : "pattern not found" );
1st Aug 2020, 5:22 PM
zemiak