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"
2 Answers
+ 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
0
System.out.println( m.find() ? word : "pattern not found" );