Validating email address in java - java

How exactly do i validate the domain part of an email address? Do i need to first list out the existing domains in my java class or java's InternetAddress.validate() will perform it by default? I have used this:
public static boolean verifyEmailAddress(String regEmail) {
boolean result = true;
try {
InternetAddress emailAddr = new InternetAddress(regEmail);
emailAddr.validate();
} catch (AddressException ex) {
result = false;
}
return result;
}
The request.getParameter has an email address and stored in regEmail..
The problem is even for invalid emails like san#hhhgggmail.com its showing valid.. What exactly do i need to do.. Help me out.. And also is this function working fine to those who have used it and tested ?

I think you are approaching the problem from the wrong perspective. From your application point of view, an email should be considered valid (better, useful) if it can receive mail. That's why all those forums keep sending you activation email :) You should send some random string to every new email address and keep it in a quarantine state until the user can prove he read the secret.
This is because the domain could exist, or even an MX record for that domain can exist in DNS, but neither of these conditions can guarantee that the address is valid - again, when you validate something you are really stating that it can be used later in your code for some purpose, and the purpose for an email address is to receive mail

I don't know if there is an automatically way in Java. But I would lookup for a MX record of the domain. If a MX record exists the domain can potentially get mails.
See also this page for more informations.

Why don't you use InetAddres.getByName on the domain part?

I think there are no exactly effective way to vefy it. all we can do is to vefy the pattern, or more you vefy the mail domain such as hhhgggmail.com. but how could you vefy that "san#hhhgggmail.com do exist" ?
SMTP do has a command 'VEFY' but almost all smtp server doesn't implement this command for security reason.
oh, you want to vefy domain. all smtp server need a mx dns record. you can use dnsjava module to validate it. code as :
public static MXRecord digOptimalMxRecords(String domainName) throws TextParseException {
List<MXRecord> records = DNSHelper.digMxRecords(domainName);
if (CollectionUtils.isNotEmpty(records)) {
Collections.sort(records, new Comparator<MXRecord>() {
#Override
public int compare(MXRecord o1, MXRecord o2) {
return o2.getPriority() - o1.getPriority();
}
});
return records.get(0);
}
return null;
}
public static List<MXRecord> digMxRecords(String domainName) throws TextParseException {
List<MXRecord> list = new ArrayList<MXRecord>();
Lookup mxLookupper = new Lookup(domainName, Type.MX);
mxLookupper.run();
if (mxLookupper.getResult() == Lookup.SUCCESSFUL) {
Record[] answers = mxLookupper.getAnswers();
for (Record record : answers) {
list.add((MXRecord) record);
}
}
return list;
}

Please ignore the variable names as they are unprofessional:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;
public class EmailValidator {
public static void main(String[] args) {
recursion();
}
static void recursion () {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the game of typing a correct email address!");
System.out.println();
System.out.println("As the game says, enter a correct email address.");
System.out.println();
String snow = scanner.nextLine();
String[] sssp = snow.split("#");
if (sssp.length != 2) {
System.out.println();
System.out.println("This is not a correct email address.");
System.out.println();
recursion();
} else {
String regex = "[^a-z0-9._]";
String regex1 = "^\\.|\\.$";
String regex2 = "\s";
String regex3 = "^$";
String regex7 = "\\._|_\\.";
String regex39 = "__";
String regex19 = "\\.\\.";
String regex20 = "^_|_$";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Pattern pattern1 = Pattern.compile(regex1, Pattern.CASE_INSENSITIVE);
Pattern pattern2 = Pattern.compile(regex2, Pattern.CASE_INSENSITIVE);
Pattern pattern3 = Pattern.compile(regex3, Pattern.CASE_INSENSITIVE);
Pattern pattern11 = Pattern.compile(regex7, Pattern.CASE_INSENSITIVE);
Pattern pattern12 = Pattern.compile(regex19, Pattern.CASE_INSENSITIVE);
Pattern pattern13 = Pattern.compile(regex20, Pattern.CASE_INSENSITIVE);
Pattern pattern14 = Pattern.compile(regex39, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(sssp[0]);
Matcher matcher1 = pattern1.matcher(sssp[0]);
Matcher matcher2 = pattern2.matcher(sssp[0]);
Matcher matcher3 = pattern3.matcher(sssp[0]);
Matcher matcher11 = pattern11.matcher(sssp[0]);
Matcher matcher12 = pattern12.matcher(sssp[0]);
Matcher matcher13 = pattern13.matcher(sssp[0]);
Matcher matcher14 = pattern14.matcher(sssp[0]);
boolean matchFound = matcher.find();
boolean matchFound1 = matcher1.find();
boolean matchFound2 = matcher2.find();
boolean matchFound3 = matcher3.find();
boolean matchFound10 = matcher11.find();
boolean matchFound11 = matcher12.find();
boolean matchFound12 = matcher13.find();
boolean matchFound13 = matcher14.find();
String hello = sssp[1];
String[] whoop = hello.split("\\.", 2);
if (whoop.length != 2) {
System.out.println();
System.out.println("This is not a correct email address.");
System.out.println();
recursion();
} else {
String regex4 = "[^a-z]";
String regex5 = "^$";
String regex6 = "\s";
Pattern pattern4 = Pattern.compile(regex4, Pattern.CASE_INSENSITIVE);
Pattern pattern5 = Pattern.compile(regex5, Pattern.CASE_INSENSITIVE);
Pattern pattern6 = Pattern.compile(regex6, Pattern.CASE_INSENSITIVE);
Matcher matcher4 = pattern4.matcher(whoop[0]);
Matcher matcher5 = pattern5.matcher(whoop[0]);
Matcher matcher6 = pattern6.matcher(whoop[0]);
boolean matchFound4 = matcher4.find();
boolean matchFound5 = matcher5.find();
boolean matchFound6 = matcher6.find();
Pattern pattern7 = Pattern.compile(regex4, Pattern.CASE_INSENSITIVE);
Pattern pattern8 = Pattern.compile(regex5, Pattern.CASE_INSENSITIVE);
Pattern pattern9 = Pattern.compile(regex6, Pattern.CASE_INSENSITIVE);
Matcher matcher7 = pattern7.matcher(whoop[1]);
Matcher matcher8 = pattern8.matcher(whoop[1]);
Matcher matcher9 = pattern9.matcher(whoop[1]);
boolean matchFound7 = matcher7.find();
boolean matchFound8 = matcher8.find();
boolean matchFound9 = matcher9.find();
System.out.println();
if(matchFound || matchFound1 || matchFound2 || matchFound3 || matchFound4 || matchFound5 || matchFound6 || matchFound7 || matchFound8 || matchFound9 || matchFound10 || matchFound11 || matchFound12 || matchFound13) {
System.out.println("This is not a correct email address.");
System.out.println();
recursion();
} else {
System.out.println("This is a correct email address.");
System.out.println();
System.out.println("Do you still want to play? (say yes to play) ");
System.out.println();
Scanner scanner1 = new Scanner(System.in);
String snow1 = scanner1.nextLine();
if (snow1.equalsIgnoreCase("yes")) {
System.out.println();
recursion();
} else {
System.out.println();
System.out.println("Okay, then.");
scanner.close();
scanner1.close();
}
}
}
}
}
}

Related

How can i extract substring from the string using regex in Java?

I have a String xxxxxxxxsrc="/slm/attachment/63338424306/Note.jpg"xxxxxxxx Now, I want to extract substrings slm/attachment/63338424306/Note.jpg & Note.jpg from the String in to variables i.e. temp1 & temp2.
How can I do that using regex in Java?
Note: 63338424306 could be any random no. & Note.jpg could be anything
like Note.png or abc.jpg or xxxx.yyy etc.
Please help me to extract these two strings using regex.
You can use negative look behind to get file name
((?:.(?<!/))+)\"
and below regex to get full path
/(.*)\"
Sample code
public static void main(String[] args) {
Pattern pattern = Pattern.compile("/(.*)\"");
Pattern pattern1 = Pattern.compile("((?:.(?<!/))+)\"");
String matchString = "/slm/attachment/63338424306/Note.jpg\"xxxxxxxx";
Matcher matcher = pattern.matcher(matchString);
String fullString = "";
while (matcher.find()) {
fullString = matcher.group(1);
}
matcher = pattern1.matcher(matchString);
String fileName = "";
while (matcher.find()) {
fileName = matcher.group(1);
}
System.out.println(fullString + " " + fileName);
}
As per your comment taking the string as declared below in my code:
Please clarify if your input string is not like this or I'm missing something.
public static void main(String[] args) {
String str = "xxxxxxxxsrc=\"/slm/attachment/63338424306/Note.jpg\"xxxxxxxx";
String url = null;
// The below pattern will grab string between quotes
Pattern p = Pattern.compile("\"([^\"]*)\"");
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println(m.group(1));
url = m.group(1);
}
// and this will grab filename from the path(url)
p = Pattern.compile("(?:.(?<!/))+$");
m = p.matcher(url);
while (m.find()) {
System.out.println(m.group());
}
}

How to get exact match keyword from the given string using java?

I'm trying to match exact AdvanceJava keyword with the given inputText string but it executes both if and else condition,instead of I want only AdvanceJava keyword matched.
String inputText = ("iwanttoknowrelatedtoAdvancejava").toLowerCase().replaceAll("\\s", "");
String match = "java";
List keywordsList = new ArrayList<>();//where keywordsList{advance,core,programming} -> keywordlist fetch
// from database
Enumeration e = Collections.enumeration(keywordsList);
int size = keywordsList.size();
while (e.hasMoreElements()) {
for (int i = 0; i < size; i++) {
String s1 = (String) keywordsList.get(i);
if (inputText.contains(s1) && inputText.contains(match)) {
System.out.println("Yes we providing " + s1);
} else if (!inputText.contains(s1) && inputText.contains(match)) {
System.out.println("Yes we are working on java");
}
}
break;
}
Thanks
you can simply do this by using pattern and matcher classes
Pattern p = Pattern.compile("java");
Matcher m = p.matcher("Print this");
m.find();
If you want to find multiple matches in a line, you can call find() and group() repeatedly to extract them all.
Here's how you can achieve what you seek using pattern matching.
In the first example I have taken your input text as it is. This only improves your algorithm which has O(n^2) performance.
String inputText = ("iwanttoknowrelatedtoAdvancejava").toLowerCase().replaceAll("\\s", "");
String match = "java";
List<String> keywordsList = Arrays.asList("advance", "core", "programming");
for (String keyword : keywordsList) {
Pattern p = Pattern.compile(keyword.concat(match));
Matcher m = p.matcher(inputText);
//System.out.println(m.find());
if (m.find()) {
System.out.println("Yes we are providing " + keyword.concat(match));
}
}
But we can improve this in to a better implementation. Here's a more generic version of the above implementation. This code doesn't manipulate the input text before matching, rather we provide a more generic regular expression which ignores spaces and matches case insensitive manner.
String inputText = "i want to know related to Advance java";
String match = "java";
List<String> keywordsList = Arrays.asList("advance", "core", "programming");
for (String keyword : keywordsList) {
Pattern p = Pattern.compile(MessageFormat.format("(?i)({0}\\s*{1})", keyword, match));
Pattern p1 = Pattern.compile(MessageFormat.format("(?i)({0})", match));
Matcher m = p.matcher(inputText);
Matcher m1 = p1.matcher(inputText);
//System.out.println(m.find());
if(m.find()) {
System.out.println("Yes we are providing " + keyword.concat(match));
} else if(m1.find()) {
System.out.println("Yes we are working with " + match);
}
}
#sithum - Thanks but it executes both condition of if else in output.Please refer Screen shot which I attached here.
I applied following logic and it works fine. please refer it , Thanks.
String inputText = ("iwanttoknowrelatedtoAdvancejava").toLowerCase().replaceAll("\\s", "");
String match = "java";
List<String> keywordsList = session.createSQLQuery("SELECT QUESTIONARIES_RAISED FROM QUERIES").list(); // Fetch values from database (advance,core,programming)
String uniqueKeyword=null;
String commonKeyword= null;
int size =keywordsList.size();
for(int i=0;i<size;i++){
String s1 = (String) keywordsList.get(i);//get values one by one from list
if(inputText.contains(match)){
if(inputText.contains(s1) && inputText.contains(match)){
Queries q1 = new Queries();
q1.setQuestionariesRaised(s1); //set matched keyword to getter setter method
keywordsList1=session.createQuery("from Queries sentence where questionariesRaised='"+q1.getQuestionariesRaised()+"'").list(); // based on matched keyword fetch according to matched keyword sentence which stored in database
for(Queries ob : keywordsList1){
uniqueKeyword= ob.getSentence().toString();// Store fetched sentence to on string variable
}
break;
}else {
commonKeyword= "java only";
}
}
}}
if(uniqueKeyword!= null){
System.out.println("Yes we providing......................" + uniqueKeyword);
}else if(commonKeyword!= null){
System.out.println("Yes we providing " + commonKeyword);
}else{
}

How to use Pattern.compile with spaces in Java?

I have a problem with matching the two words with a space between them in Pattern.compile in Java.
My string is "What is your name?".
My code:
String namee = "What is your name?";
Pattern pattern = Pattern.compile("What is|Address is");
if (pattern.matcher(namee).find())
{
if (namee.equals("What is"))
{
namee = "name";
}
}
what I am trying to achieve if a string consist "What is" then the string itself should change to "name". But its not wotking with space...
Solution1
You can use Matcher and then check with the matcher.group() like this:
Pattern pattern = Pattern.compile("What is|Address is");
Matcher matcher = pattern.matcher(namee);
if (matcher.find()) {
if (matcher.group().equals("What is")) {
namee = "name";
}
}
Solution2
If you want to check if your string contain What is or Address is, then you can easily use :
if(namee.contains("What is")){
namee = "What is";
}else if (namee.contains("Address is")){
namee = "....";
}
Solution3
If you want to check if your string start with What is or Address is then you can use :
if(namee.startsWith("What is")){
namee = "What is";
}else if (namee.startsWith("Address is")){
namee = "....";
}
Try like this (to be safe; better code readability as well IMHO):
Pattern pattern = Pattern.compile("(What is)|(Address is)")
but the following code feels wrong:
if (namee.equals("What is"))
...
you probably want to use instead the java.util.regex.Matcher you just created. For instance:
Matcher matcher = pattern.matcher(namee);
if (matcher.find()) {
if (matcher.group().equals("What is")) {
...
}
}

check for string after a string

I'm writing a logic to check if there is any number following a specific keyword ("top" in the case).
String test = "top 10 results";
String test = "show top 10 results";
I used the pattern match find to acheive that and its working.
public static boolean hasNumberafterTOP(String query)
{
boolean hasNumberafterTOP = false;
Pattern pat = Pattern.compile("top\\s+([0-9]+)");
Matcher matcher = pat.matcher(query);
if(matcher.find())
{
hasNumberafterTOP = true;
numberAfterTOP=matcher.group(1);
}
return hasNumberafterTOP;
}
Is there any way I can extend this check to include these words too. five,ten,twenty,thirty etc.?
Try this code:
String keyword = "top";
Pattern p= Pattern.compile("\\d*\\s+"+Pattern.quote(keyword));
Matcher match = p.matcher(query");
match .find();
String inputInt = makeMatch.group();
System.out.println(inputInt);

How to get the video id from a YouTube URL with regex in Java

Porting from javascript answer to Java version
JavaScript REGEX: How do I get the YouTube video id from a URL?
Figured this question wasn't here for Java, in case you need to do it in Java here's a way
public static String extractYTId(String ytUrl) {
String vId = null;
Pattern pattern = Pattern.compile(
"^https?://.*(?:youtu.be/|v/|u/\\w/|embed/|watch?v=)([^#&?]*).*$",
Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(ytUrl);
if (matcher.matches()){
vId = matcher.group(1);
}
return vId;
}
Works for URLs like (also for https://...)
http://www.youtube.com/watch?v=0zM4nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/SomeUser#p/a/u/1/QDK8U-VIH_o
http://www.youtube.com/v/0zM4nApSvMg?fs=1&hl=en_US&rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM4nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg
http://youtu.be/0zM4nApSvMg
Previous answers don't work for me.. It's correct method. It works with www.youtube.com and youtu.be links.
private String getYouTubeId (String youTubeUrl) {
String pattern = "(?<=youtu.be/|watch\\?v=|/videos/|embed\\/)[^#\\&\\?]*";
Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(youTubeUrl);
if(matcher.find()){
return matcher.group();
} else {
return "error";
}
}
Update 21 Oct 2022
As this post getting attention from people, I am going to update to serve more cases, thanks to #Nikhil Seban for your new links, the Java code is remained thanks to guys provide code #Leap Bun #Pankaj
This regex also use match group(1), please take a look on the bottom
Regex Online Here
http(?:s)?:\/\/(?:m.)?(?:www\.)?youtu(?:\.be\/|(?:be-nocookie|be)\.com\/(?:watch|[\w]+\?(?:feature=[\w]+.[\w]+\&)?v=|v\/|e\/|embed\/|user\/(?:[\w#]+\/)+))([^&#?\n]+)
http://www.youtube.com/watch?v=0zM4nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/SomeUser#p/a/u/1/QDK8U-VIH_o
http://www.youtube.com/v/0zM4nApSvMg?fs=1&hl=en_US&rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM4nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg
http://youtu.be/0zM4nApSvMg
https://www.youtube.com/watch?v=nBuae6ilH24
https://www.youtube.com/watch?v=pJegNopBLL8
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
https://www.youtube.com/watch?v=0zM4nApSvMg&feature=youtu.be
https://www.youtube.com/watch?v=_5BTo2oZ0SE
https://m.youtube.com/watch?feature=youtu.be&v=_5BTo2oZ0SE
https://m.youtube.com/watch?v=_5BTo2oZ0SE
https://www.youtube.com/watch?feature=youtu.be&v=_5BTo2oZ0SE&app=desktop
https://www.youtube.com/watch?v=nBuae6ilH24
https://www.youtube.com/watch?v=eLlxrBmD3H4
https://www.youtube.com/watch?v=DFYRQ_zQ-gk&feature=featured
https://www.youtube.com/watch?v=DFYRQ_zQ-gk
http://www.youtube.com/watch?v=DFYRQ_zQ-gk
http://www.youtube.com/watch?v=DFYRQ_zQ-gk
http://www.youtube.com/watch?v=DFYRQ_zQ-gk
https://youtube.com/watch?v=DFYRQ_zQ-gk
http://youtube.com/watch?v=DFYRQ_zQ-gk
https://youtube.com/watch?v=DFYRQ_zQ-gk
http://youtube.com/watch?v=DFYRQ_zQ-gk
https://m.youtube.com/watch?v=DFYRQ_zQ-gk
http://m.youtube.com/watch?v=DFYRQ_zQ-gk
http://m.youtube.com/watch?v=DFYRQ_zQ-gk
http://m.youtube.com/watch?v=DFYRQ_zQ-gk
https://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
https://www.youtube.com/embed/DFYRQ_zQ-gk?autoplay=1
https://www.youtube.com/embed/DFYRQ_zQ-gk
http://www.youtube.com/embed/DFYRQ_zQ-gk
http://www.youtube.com/embed/DFYRQ_zQ-gk
http://www.youtube.com/embed/DFYRQ_zQ-gk
https://youtube.com/embed/DFYRQ_zQ-gk
http://youtube.com/embed/DFYRQ_zQ-gk
http://youtube.com/embed/DFYRQ_zQ-gk
https://youtube.com/embed/DFYRQ_zQ-gk
https://youtu.be/DFYRQ_zQ-gk?t=120
https://youtu.be/DFYRQ_zQ-gk
http://youtu.be/DFYRQ_zQ-gk
http://youtu.be/DFYRQ_zQ-gk
http://youtu.be/DFYRQ_zQ-gk
https://www.youtube.com/HamdiKickProduction?v=DFYRQ_zQ-gk
https://www.youtube.com/watch?v=wz4MLJBdSpw&t=67s
http://www.youtube.com/watch?v=dQw4w9WgXcQ&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW
http://www.youtube.com/embed/dQw4w9WgXcQ
http://www.youtube.com/watch?v=dQw4w9WgXcQ
https://www.youtube.com/watch?v=EL-UCUAt8DQ
http://www.youtube.com/watch?v=dQw4w9WgXcQ
http://youtu.be/dQw4w9WgXcQ
http://www.youtube.com/v/dQw4w9WgXcQ
http://www.youtube.com/e/dQw4w9WgXcQ
http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
https://www.youtube-nocookie.com/embed/xHkq1edcbk4?rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/SomeUser#p/a/u/1/QDK8U-VIH_o
http://www.youtube.com/v/0zM4nApSvMg?fs=1&hl=en_US&rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM4nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg
http://youtu.be/0zM4nApSvMg
Old post
This below code you can also use either review what I have updated or develop new pattern
I know this topic is old, but I get more cases to get Youtube id, this is my regex
http(?:s)?:\/\/(?:m.)?(?:www\.)?youtu(?:\.be\/|be\.com\/(?:watch\?(?:feature=youtu.be\&)?v=|v\/|embed\/|user\/(?:[\w#]+\/)+))([^&#?\n]+)
This will work for
http://www.youtube.com/watch?v=0zM4nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/user/SomeUser#p/a/u/1/QDK8U-VIH_o
http://www.youtube.com/v/0zM4nApSvMg?fs=1&hl=en_US&rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
http://www.youtube.com/embed/0zM4nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM4nApSvMg
http://youtu.be/0zM4nApSvMg
https://www.youtube.com/watch?v=nBuae6ilH24
https://www.youtube.com/watch?v=pJegNopBLL8
http://www.youtube.com/watch?v=0zM4nApSvMg#t=0m10s
https://www.youtube.com/watch?v=0zM4nApSvMg&feature=youtu.be
https://www.youtube.com/watch?v=_5BTo2oZ0SE
https://m.youtube.com/watch?feature=youtu.be&v=_5BTo2oZ0SE
https://m.youtube.com/watch?v=_5BTo2oZ0SE
https://www.youtube.com/watch?feature=youtu.be&v=_5BTo2oZ0SE&app=desktop
https://www.youtube.com/watch?v=nBuae6ilH24
https://www.youtube.com/watch?v=eLlxrBmD3H4
Note: Using regex match group(1) to get ID
public static String getVideoId(#NonNull String videoUrl) {
String videoId = "";
String regex = PLEASE_COPY_ABOVE_REGEX_PATTERN
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(url);
if(matcher.find()){
videoId = matcher.group(1);
}
return videoId;
}
To me, for the sample links you posted, this regex looks more precise (capturing the ID to Group 1):
https?://(?:www\.)?youtu(?:\.be/|be\.com/(?:watch\?v=|v/|embed/|user/(?:[\w#]+/)+))([^&#?\n]+)
On the demo, see the capture groups in the bottom right pane. However, for the second match, not entirely sure that this is a correct ID as it looks different from the other samples—to be tweaked if needed.
In code, something like:
Pattern regex = Pattern.compile("http://(?:www\\.)?youtu(?:\\.be/|be\\.com/(?:watch\\?v=|v/|embed/|user/(?:[\\w#]+/)+))([^&#?\n]+)");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
VideoID = regexMatcher.group(1);
}
private fun extractVideoId(ytUrl: String?): String? {
var videoId: String? = null
val regex =
"^((?:https?:)?//)?((?:www|m)\\.)?((?:youtube\\.com|youtu.be|youtube-nocookie.com))(/(?:[\\w\\-]+\\?v=|feature=|watch\\?|e/|embed/|v/)?)([\\w\\-]+)(\\S+)?\$"
val pattern: Pattern = Pattern.compile(
regex ,
Pattern.CASE_INSENSITIVE
)
val matcher: Matcher = pattern.matcher(ytUrl)
if (matcher.matches()) {
videoId = matcher.group(5)
}
return videoId
}
The above function with regex can extract video Id from
https://www.youtube.com/watch?v=DFYRQ_zQ-gk&feature=featured
https://www.youtube.com/watch?v=DFYRQ_zQ-gk
http://www.youtube.com/watch?v=DFYRQ_zQ-gk
http://www.youtube.com/watch?v=DFYRQ_zQ-gk
http://www.youtube.com/watch?v=DFYRQ_zQ-gk
https://youtube.com/watch?v=DFYRQ_zQ-gk
http://youtube.com/watch?v=DFYRQ_zQ-gk
https://youtube.com/watch?v=DFYRQ_zQ-gk
http://youtube.com/watch?v=DFYRQ_zQ-gk
https://m.youtube.com/watch?v=DFYRQ_zQ-gk
http://m.youtube.com/watch?v=DFYRQ_zQ-gk
http://m.youtube.com/watch?v=DFYRQ_zQ-gk
http://m.youtube.com/watch?v=DFYRQ_zQ-gk
https://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://www.youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
http://youtube.com/v/DFYRQ_zQ-gk?fs=1&hl=en_US
https://www.youtube.com/embed/DFYRQ_zQ-gk?autoplay=1
https://www.youtube.com/embed/DFYRQ_zQ-gk
http://www.youtube.com/embed/DFYRQ_zQ-gk
http://www.youtube.com/embed/DFYRQ_zQ-gk
http://www.youtube.com/embed/DFYRQ_zQ-gk
https://youtube.com/embed/DFYRQ_zQ-gk
http://youtube.com/embed/DFYRQ_zQ-gk
http://youtube.com/embed/DFYRQ_zQ-gk
https://youtube.com/embed/DFYRQ_zQ-gk
https://youtu.be/DFYRQ_zQ-gk?t=120
https://youtu.be/DFYRQ_zQ-gk
http://youtu.be/DFYRQ_zQ-gk
http://youtu.be/DFYRQ_zQ-gk
http://youtu.be/DFYRQ_zQ-gk
https://www.youtube.com/HamdiKickProduction?v=DFYRQ_zQ-gk
https://www.youtube.com/watch?v=wz4MLJBdSpw&t=67s
http://www.youtube.com/watch?v=dQw4w9WgXcQ&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW
http://www.youtube.com/embed/dQw4w9WgXcQ
http://www.youtube.com/watch?v=dQw4w9WgXcQ
https://www.youtube.com/watch?v=EL-UCUAt8DQ
http://www.youtube.com/watch?v=dQw4w9WgXcQ
http://youtu.be/dQw4w9WgXcQ
http://www.youtube.com/v/dQw4w9WgXcQ
http://www.youtube.com/e/dQw4w9WgXcQ
http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
Tried the other ones but failed in my case - adjusted the regex to fit for my urls
public static String extractYoutubeVideoId(String ytUrl) {
String vId = null;
String pattern = "(?<=watch\\?v=|/videos/|embed\\/)[^#\\&\\?]*";
Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(ytUrl);
if(matcher.find()){
vId= matcher.group();
}
return vId;
}
This one works for below url's
http://www.youtube.com/embed/Woq5iX9XQhA?html5=1
http://www.youtube.com/watch?v=384IUU43bfQ
http://gdata.youtube.com/feeds/api/videos/xTmi7zzUa-M&whatever
https://www.youtube.com/watch?v=C7RVaSEMXNk
Hope it will help some one. Thanks
Using regex from Tấn Nguyên:
public String getVideoIdFromYoutubeUrl(String url){
String videoId = null;
String regex = "http(?:s)?:\\/\\/(?:m.)?(?:www\\.)?youtu(?:\\.be\\/|be\\.com\\/(?:watch\\?(?:feature=youtu.be\\&)?v=|v\\/|embed\\/|user\\/(?:[\\w#]+\\/)+))([^&#?\\n]+)";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(url);
if(matcher.find()){
videoId = matcher.group(1);
}
return videoId;
}
Credit to Tấn Nguyên.
This will work for me and simple..
public static String getVideoId(#NonNull String videoUrl) {
String reg = "(?:youtube(?:-nocookie)?\\.com\\/(?:[^\\/\\n\\s]+\\/\\S+\\/|(?:v|e(?:mbed)?)\\/|\\S*?[?&]v=)|youtu\\.be\\/)([a-zA-Z0-9_-]{11})";
Pattern pattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(videoUrl);
if (matcher.find())
return matcher.group(1);
return null;
}
Just pass youtube link in below function , it will detect all type of youtube url
public static String getYoutubeID(String youtubeUrl) {
if (TextUtils.isEmpty(youtubeUrl)) {
return "";
}
String video_id = "";
String expression = "^.*((youtu.be" + "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*).*"; // var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
CharSequence input = youtubeUrl;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
String groupIndex1 = matcher.group(7);
if (groupIndex1 != null && groupIndex1.length() == 11)
video_id = groupIndex1;
}
if (TextUtils.isEmpty(video_id)) {
if (youtubeUrl.contains("youtu.be/") ) {
String spl = youtubeUrl.split("youtu.be/")[1];
if (spl.contains("\\?")) {
video_id = spl.split("\\?")[0];
}else {
video_id =spl;
}
}
}
return video_id;
}
Combining a couple of methods, to cover as many formats as possible, is recommended.
String ID1 = getYoutubeID1(url); regex 1
String ID2 = getYoutubeID2(url); regex 2
String ID3 = getYoutubeID3(url); regex 3
then, using an if/switch statement to choose a value that isn't null and is valid.
I actully try all the above but some times work and some times fail
any way I found this may it help -- in this site
private final static String expression = "(?<=watch\\?v=|/videos/|embed\\/|youtu.be\\/|\\/v\\/|\\/e\\/|watch\\?v%3D|watch\\?feature=player_embedded&v=|%2Fvideos%2F|embed%\u200C\u200B2F|youtu.be%2F|%2Fv%2F)[^#\\&\\?\\n]*";
public static String getVideoId(String videoUrl) {
if (videoUrl == null || videoUrl.trim().length() <= 0){
return null;
}
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(videoUrl);
try {
if (matcher.find())
return matcher.group();
} catch (ArrayIndexOutOfBoundsException ex) {
ex.printStackTrace();
}
return null;
}
he said
This will work on two kinks of youtube video urls either direct or shared URL.
Direct url: https://www.youtube.com/watch?v=XXXXXXXXXXX
Shared url: https://youtu.be/XXXXXXXXXXX
This is very similar to the link posted in your question.
String url = "https://www.youtube.com/watch?v=wZZ7oFKsKzY";
if(url.indexOf("v=") == -1) //there's no video id
return "";
String id = url.split("v=")[1]; //everything before the first 'v=' will be the first element, i.e. [0]
int end_of_id = id_to_end.indexOf("&"); //if there are other parameters in the url, get only the id's value
if(end_index != -1)
id = url.substring(0, end_of_id);
return id;
Without regex :
String url - "https://www.youtube.com/watch?v=BYrumLBuzHk"
String video_id = url.replace("https://www.youtube.com/watch?v=", "")
So now you have a video ID in string video_id.

Categories