Search code examples
javaregexsubstring

Line break after substring


If I use a pattern and matcher in Java how can I add a line break right after I find the substring? UPDATE

I found a solution using the replaceAll(String,String); method

Thanks a lot guys my solution has been formatted below

 String contentsToSearch = "This is an example string /* example comment in my string */ with some extra text following my inline comment";
//String regex = "[*/]" ;
//Pattern pattern = Pattern.compile(regex);
//Matcher matcher = pattern.matcher(contentsToSearch);

//if(matcher.find()){
      // add a line break to the string i am searching
 //}else{
      // print out my string regularly
  //    System.out.println(contentsToSearch);
 //}
 contentsToSearch = contentsToSearch.replaceAll("\\*/", "\\*/\n");
 System.out.println(contentsToSearch);

Solution

  • You could simply do:

    contentsToSearch = contentsToSearch.replaceAll("(/\\*|\\*/)", "$1\n")