import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(youtu.*be.*)\\/(watch\\?v=|embed\\/|v|shorts|)(.*?((?=[&#?])))";
final String string = "<p>http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index <br><br>https://youtube.com/shorts/0dPkkQeRwTI</p><h2>Para</h2>\n"
+ "<p>http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o</p><p>Para</p>\n"
+ "<p>http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0</p><p>Para</p>\n"
+ "<p><br>http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s</p><p>Para</p>\n"
+ "<p>Check out my youtube video: http://www.youtube.com/embed/0zM3nApSvMg?rel=0</p><p>Para</p>\n"
+ "<p>http://www.youtube.com/watch?v=0zM3nApSvMg</p><p>Para</p>\n"
+ "<p><br>http://youtu.be/0zM3nApSvMg</p><p>Para</p>\n"
+ "<div>https://youtube.com/shorts/0dPkkQeRwTI?feature=share</div>\n"
+ "<p>https://youtube.com/shorts/0dPkkQeRwTI</p><p>Para</p>\n"
+ "<p>https://www.youtube.com/watch?v=0dPkkQeRwTI&ab_channel=RelaxedChan</p><p>Para</p>";
final String subst = "<iframe width=\"100%\" src=\"https://www.youtube.com/embed/$3\" frameborder=\"0\" allowfullscreen></iframe>";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);
System.out.println("Substitution result: " + result);
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html