EditText validation not working as expected - java

I have developed android application and in there I have front end validation to a EditText field where its accept only three alpha and 4 digits.
It is tested in staging environment and front end validation is working perfectly (We don’t have back end validation). But after some time when we check
On our live database. We found some data with only digits relevant to above mentioned field. It seems somehow validation will not effect in some device
And we have received data with only digits. Is it possible or what can be the reason that we received invalid data.
// Check for id is valid format like "ABC1234".
String alphaLen = getResources().getString(R.string.rokaIdAlphaLen);
String numLen = getResources().getString(R.string.rokaIdNumericLen);
if (rokaId.length() > 0 && !Validate.validateRokaId(rokaId, alphaLen, numLen)) {
etRokaid.setError(getString(R.string.error_incorrect_format));
focusView = etRokaid;
cancel = true;
}
public static boolean validateRokaId(String params, String alphaLen, String numLen) {
boolean success = false;
int alphaLength = 0;
int numericLength = 0;
alphaLength = Integer.parseInt(alphaLen.trim());
numericLength = Integer.parseInt(numLen.trim());
if (params.length() == alphaLength + numericLength) {
if (params.substring(0, alphaLength).matches("[a-zA-Z]*")) {
if (params.substring(alphaLength, alphaLength+numericLength).matches("[0-9]*")) {
success = true;
} else {
success = false;
}
} else {
success = false;
}
} else {
success = false;
}
return success;
}

First of all you need to set Edit Text property android:digits in XML file for more security so no other special character to be inserted by the user even if you checked in validation.
android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
Now for your format which is 3 character and 4 digit we create a Regex expression. You can create your own Regex Expression and test it from this site. I create this Regex from this site:
[A-Z]{3}\d{4}
public final static Pattern NAME_PATTERN = Pattern.compile("^[A-Z]{3}[0-9]{4}$");
Now just match this pattern.
if (NAME_PATTERN.matcher(edtText.getText().toString().trim()).matches())
{
// Write your logic if pattern match
}
else
{
// Write your logic if pattern not match
}

Related

Wrong values when matching strings of html tags

I've been working on something that checks if an HTML file is well-formed (No self-closing tags for simplicity). I filtered everything but the text of the tag and the "/" if it has one using splits. Ex: p, /p
I'm getting a value of true for things such as "head, title, /head, /title", but it is passing all of my other test cases..
My logic for seeing if these are well-formed is to dequeue the tags, if it does not contain "/" push into a stack, if it does I check to see if the value from my queue matches the pop value from my stack etc.
I feel like I'm making some kind of basic logical error that I'm just not seeing after staring at it for so long.
while (!tags.isEmpty()) {
try {
temp = tags.dequeue();
if (!temp.contains("/")) {
openTags.push(temp);
counter++;
}
if (temp.contains("/")) {
String open = openTags.pop();
split = temp.split("/");
temp = split[1];
if (counter == 0) { //check if first item contained "/" (automatically invalid)
return false;
}
if (!temp.equalsIgnoreCase(open)) {
return false;
}
}
} catch (EmptyCollectionException ex) {
Logger.getLogger(TagValidation.class.getName()).log(Level.SEVERE, null, ex);
}
}

Check multiple Boolean condition in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have a scenario in which I have to check whether the template exists already in the database. If it exists I have to return a message based on the existing template.
I have several templates: Email, Letter, SMS. If all of them exist I have to return "All template exist already."
If only the Email template exists I have to return that only the email template exists, same for Letter and Sms templates.
Code:
for (EventVO eventVO: eventModuleList) {
List <EmailTemplateMaster> emailTemplateList = communicationDAO
.checkEmailTemplateExist(eventVO.getEventCode());
if (CollectionUtils.isNotEmpty(emailTemplateList)) {
emailTemplateExist = true;
}
List <LetterTemplateMaster> letterTemplateList = communicationDAO
.checkLetterTemplateExist(eventVO.getEventCode());
if (CollectionUtils.isNotEmpty(letterTemplateList)) {
letterTemplateExist = true;
}
List <SmsTemplateMaster> smsTemplateList = communicationDAO
.checkSmsTemplateExist(eventVO.getEventCode());
if (CollectionUtils.isNotEmpty(smsTemplateList)) {
smsTemplateExist = true;
}
if (emailTemplateExist && letterTemplateExist && smsTemplateExist) {
templateExist = CommunicationConstants.ALL_TEMPLATE_EXIST;
}
if (emailTemplateExist || !letterTemplateExist && !smsTemplateExist) {
templateExist = CommunicationConstants.EMAIL_TEMPLATE_EXIST;
}
if (!emailTemplateExist && letterTemplateExist && !smsTemplateExist) {
templateExist = CommunicationConstants.LETTER_TEMPLATE_EXIST;
}
if (!emailTemplateExist && !letterTemplateExist && smsTemplateExist) {
templateExist = CommunicationConstants.SMS_TEMPLATE_EXIST;
}
}
Can I know the easiest way to check the Boolean value of exit template exist.
Based on exit, I have to sent the corresponding message.
public static final String ALL_TEMPLATE_EXIST = "Email, Letter and Sms Template already exist for the selected event.";
public static final String EMAIL_TEMPLATE_EXIST = "Email Template already exist for the selected event.";
public static final String SMS_TEMPLATE_EXIST = "Sms Template already exist for the selected event.";
public static final String LETTER_TEMPLATE_EXIST = "Email Letter Template already exist for the selected event.";
public static final String EMAIL_SMS_TEMPLATE_EXIST = "Email and Sms Template already exist for the selected event.";
public static final String EMAIL_LETTER_TEMPLATE_EXIST = "Email and Letter Template already exist for the selected event.";
public static final String SMS_LETTER_TEMPLATE_EXIST = "Sms and Letter Template already exist for the selected event.";
You could "prepare" the mapping between the booleans and the messages in the CommunicationConstants class:
public class CommunicationConstants
{
private static final Map<List<Boolean>, String> CONSTANTS = new HashMap<>();
static
{
CONSTANTS.put(Arrays.asList(true, true, true), "Email, Letter and Sms Template already exist for the selected event.");
CONSTANTS.put(Arrays.asList(true, true, false), "Email and Sms Template already exist for the selected event.");
CONSTANTS.put(Arrays.asList(true, false, true), "Email and Letter Template already exist for the selected event.");
CONSTANTS.put(Arrays.asList(false, true, true), "Sms and Letter Template already exist for the selected event.");
CONSTANTS.put(Arrays.asList(true, false, false), "Email Template already exist for the selected event.");
CONSTANTS.put(Arrays.asList(false, true, false), "Sms Template already exist for the selected event.");
CONSTANTS.put(Arrays.asList(false, false, true), "Letter Template already exist for the selected event.");
}
public static String getMessage(boolean emailExists, boolean smsExists, boolean letterExists)
{
return CONSTANTS.get(Arrays.asList(emailExists, smsExists, letterExists));
}
}
The code to retrieve it will be a one-liner then:
System.out.println(CommunicationConstants.getMessage(true, false, true));
If it's possible to you to change your DataBase model, do following changes:
1- Change all booleans into Template type which is VARCHAR() with following allowed values => ALL_TEMPLATE_EXIST, EMAIL_TEMPLATE_EXIST, LETTER_TEMPLATE_EXIST, SMS_TEMPLATE_EXIST
2- After reading the value from data base use only one line code to set your values:
templateExist = CommunicationConstants.valueOf(thePropertyValueYouReadFromDataBase);
Edit
By this change, taking decision of which template already exist would be up to the business code which insert template, reading part only read value of what really inserted
I would do it this way. I find it clearer but obviously every body's mind is different.
if (emailTemplateExist) {
templateExist = letterTemplateExist && smsTemplateExist ? CommunicationConstants.ALL_TEMPLATE_EXIST: CommunicationConstants.EMAIL_TEMPLATE_EXIST;
}
else{
if (letterTemplateExist && !smsTemplateExist)
templateExist = CommunicationConstants.LETTER_TEMPLATE_EXIST;
else if (!letterTemplateExist && smsTemplateExist)
templateExist = CommunicationConstants.SMS_TEMPLATE_EXIST;
}
// There is a possiblity that you will end up with a null value in templateExist so you should initialize it with some default.
In my opinion, you are missing several cases… However, you can do it by nesting if statements. Please note that I added a value to the enum that represents the case of no template existing in the database. With this approach, you will need additional enum values for email and sms, email and letter and letter and sms. If you are sure those cases will never happen, then this approach covers too much.
public static void main(String[] args) {
boolean emailTemplateExist = true;
boolean letterTemplateExist = true;
boolean smsTemplateExist = true;
CommunicationConstants templateExist = CommunicationConstants.NO_TEMPLATE_EXIST;
if (emailTemplateExist) {
if (letterTemplateExist) {
if (smsTemplateExist) {
// email exists, letter exists, sms exists ==> 3/3
templateExist = CommunicationConstants.ALL_TEMPLATE_EXIST;
} else {
// email exists, letter exists, sms does not exist ==> 2/3
// what to do here?
/*
* what to do in this case? The enum has no value for that...
*/
}
} else {
if (smsTemplateExist) {
// email exists, letter does not exist, sms exists ==> 2/3
/*
* what to do in this case? The enum has no value for that...
*/
} else {
// email exists, letter does not exist, sms does not exist ==> 1/3
}
}
} else {
if (letterTemplateExist) {
if (smsTemplateExist) {
// email does not exist, letter exists, sms exists ==> 2/3
/*
* what to do in this case? The enum has no value for that...
*/
} else {
// email does not exist, letter exists, sms does not exist ==> 1/3
templateExist = CommunicationConstants.LETTER_TEMPLATE_EXIST;
}
} else {
if (smsTemplateExist) {
// email does not exist, letter does not exist, sms exists ==> 1/3
templateExist = CommunicationConstants.SMS_TEMPLATE_EXIST;
} else {
// email does not exist, letter does not exist, sms does not exist ==> 0/3
/*
* by initializing the return value with something like "NO_TEMPLATE_EXIST",
* you can omit this else block entirely
*/
templateExist = CommunicationConstants.NO_TEMPLATE_EXIST;
}
}
}
System.out.println(templateExist.toString());
}
enum CommunicationConstants {
ALL_TEMPLATE_EXIST,
EMAIL_TEMPLATE_EXIST,
LETTER_TEMPLATE_EXIST,
SMS_TEMPLATE_EXIST,
NO_TEMPLATE_EXIST
}
Just play around with the initial values (currently, they all are true).
Below code generates all combinations with single template:
public class Main {
enum TemplateType {
Email, Sms, Letter
}
private static final String MSG_EXISTS = "%s Template%s already exist%s for the selected event.";
private static int testCounter;
public static void main(String[] args) {
// Generates all combinations
for (testCounter = 0; testCounter < 8; testCounter++) {
System.out.println(testCounter + ". " + evaluate());
}
}
private static String evaluate() {
List<String> templateList = Arrays.stream(TemplateType.values())
.filter(Main::checkExistence)
.map(TemplateType::name)
.collect(Collectors.toList());
if (templateList.isEmpty()) {
return null;
}
int size = templateList.size();
String arg1 = prettyPrintListJoiner(templateList);
return String.format(MSG_EXISTS, arg1, size == 1 ? "" : "s", size == 1 ? "s" : "");
}
private static String prettyPrintListJoiner(List<String> templateList) {
int size = templateList.size();
if (size == 1) {
return templateList.get(0);
}
StringJoiner joiner = new StringJoiner(", ");
if (size > 2) {
joiner.add(String.join(", ", templateList.subList(0, size - 2)));
}
return joiner.add(String.join(" and ", templateList.subList(size - 2, size))).toString();
}
// To generate all possibilities with help of testCounter
private static boolean checkExistence(TemplateType type) {
switch (type) {
case Email:
return ((testCounter >> 2) & 1) == 1;
case Sms:
return ((testCounter >> 1) & 1) == 1;
case Letter:
return ((testCounter) & 1) == 1;
}
throw new IllegalArgumentException();
}
}
Test Output:
0. null
1. Letter Template already exists for the selected event.
2. Sms Template already exists for the selected event.
3. Sms and Letter Templates already exist for the selected event.
4. Email Template already exists for the selected event.
5. Email and Letter Templates already exist for the selected event.
6. Email and Sms Templates already exist for the selected event.
7. Email, Sms and Letter Templates already exist for the selected event.

Lucene multi word tokens with delimiter

I am just starting with Lucene so it's probably a beginners question. We are trying to implement a semantic search on digital books and already have a concept generator, so for example the contexts I generate for a new article could be:
|Green Beans | Spring Onions | Cooking |
I am using Lucene to create an index on the books/articles using only the extracted concepts (stored in a temporary document for that purpose). Now the standard analyzer is creating single word tokens: Green, Beans, Spring, Onions, Cooking, which of course is not the same.
My question: is there an analyzer that is able to detect delimiters around tokens (|| in our example), or an analyzer that is able to detect multi-word constructs?
I'm afraid we'll have to create our own analyzer, but I don't quite know where to start for that one.
Creating an analyzer is pretty easy. An analyzer is just a tokenizer optionally followed by token filters. In your case, you'd have to create your own tokenizer. Fortunately, you have a convenient base class for this: CharTokenizer.
You implement the isTokenChar method and make sure it returns false on the | character and true on any other character. Everything else will be considered part of a token.
Once you have the tokenizer, the analyzer should be straightforward, just look at the source code of any existing analyzer and do likewise.
Oh, and if you can have spaces between your | chars, just add a TrimFilter to the analyzer.
I came across this question because I am doing something with my Lucene mechanisms which creates data structures to do with sequencing, in effect "hijacking" the Lucene classes. Otherwise I can't imagine why people would want knowledge of the separators ("delimiters") between tokens, but as it was quite tricky I thought I'd put it here for the benefit of anyone who might need to.
You have to rewrite your own versions of StandardTokenizer and StandardTokenizerImpl. These are both final classes so you can't extend them.
SeparatorDeliveringTokeniserImpl (tweaked from source of StandardTokenizerImpl):
3 new fields:
private int startSepPos = 0;
private int endSepPos = 0;
private String originalBufferAsString;
Tweak these methods:
public final void getText(CharTermAttribute t) {
t.copyBuffer(zzBuffer, zzStartRead, zzMarkedPos - zzStartRead);
if( originalBufferAsString == null ){
originalBufferAsString = new String( zzBuffer, 0, zzBuffer.length );
}
// startSepPos == -1 is a "flag condition": it means that this token is the last one and it won't be followed by a sep
if( startSepPos != -1 ){
// if the flag is NOT set, record the start pos of the next sep...
startSepPos = zzMarkedPos;
}
}
public final void yyreset(java.io.Reader reader) {
zzReader = reader;
zzAtBOL = true;
zzAtEOF = false;
zzEOFDone = false;
zzEndRead = zzStartRead = 0;
zzCurrentPos = zzMarkedPos = 0;
zzFinalHighSurrogate = 0;
yyline = yychar = yycolumn = 0;
zzLexicalState = YYINITIAL;
if (zzBuffer.length > ZZ_BUFFERSIZE)
zzBuffer = new char[ZZ_BUFFERSIZE];
// reset fields responsible for delivering separator...
originalBufferAsString = null;
startSepPos = 0;
endSepPos = 0;
}
(inside getNextToken:)
if ((zzAttributes & 1) == 1) {
zzAction = zzState;
zzMarkedPosL = zzCurrentPosL;
if ((zzAttributes & 8) == 8) {
// every occurrence of a separator char leads here...
endSepPos = zzCurrentPosL;
break zzForAction;
}
}
And make a new method:
String getPrecedingSeparator() {
String sep = null;
if( originalBufferAsString == null ){
sep = new String( zzBuffer, 0, endSepPos );
}
else if( startSepPos == -1 || endSepPos <= startSepPos ){
sep = "";
}
else {
sep = originalBufferAsString.substring( startSepPos, endSepPos );
}
if( zzMarkedPos < startSepPos ){
// ... then this is a sign that the next token will be the last one... and will NOT have a trailing separator
// so set a "flag condition" for next time this method is called
startSepPos = -1;
}
return sep;
}
SeparatorDeliveringTokeniser (tweaked from source of StandardTokenizer):
Add this:
private String separator;
String getSeparator(){
// normally this delivers a preceding separator... but after incrementToken returns false, if there is a trailing
// separator, it then delivers that...
return separator;
}
(inside incrementToken:)
while(true) {
int tokenType = scanner.getNextToken();
// added NB this gives you the separator which PRECEDES the token
// which you are about to get from scanner.getText( ... )
separator = scanner.getPrecedingSeparator();
if (tokenType == SeparatorDeliveringTokeniserImpl.YYEOF) {
// NB at this point sep is equal to the trailing separator...
return false;
}
...
Usage:
In my FilteringTokenFilter subclass, called TokenAndSeparatorExamineFilter, the methods accept and end look like this:
#Override
public boolean accept() throws IOException {
String sep = ((SeparatorDeliveringTokeniser) input).getSeparator();
// a preceding separator can only be an empty String if we are currently
// dealing with the first token and if the sequence starts with a token
if (!sep.isEmpty()) {
// ... do something with the preceding separator
}
// then get the token...
String token = getTerm();
// ... do something with the token
// my filter does no filtering! Every token is accepted...:
return true;
}
#Override
public void end() throws IOException {
// deals with trailing separator at the end of a sequence of tokens and separators (if there is one, i.e. if it doesn't end with a token)
String sep = ((SeparatorDeliveringTokeniser) input).getSeparator();
// NB will be an empty String if there is no trailing separator
if (!sep.isEmpty()) {
// ... do something with this trailing separator
}
}

How can I remove the subdomain part of a URL

I am trying to remove subdomain and leave only the domain name followed by the extension.
It is difficult to find the subdomain because I do not know how many dots to expect in a url. some urls end in .com some in .co.uk for example.
How can I remove the subdomain safely so that foo.bar.com becomes bar.com and foo.bar.co.uk becomes bar.co.uk
if(!rawUrl.startsWith("http://")&&!rawUrl.startsWith("https://")){
rawUrl = "http://"+rawUrl;
}
String url = new java.net.URL(rawUrl).getHost();
String urlWithoutSub = ???
What you need is a Public Sufix List, such as the one available at https://publicsuffix.org/. Basically, there is no algorithm that can tell you which suffixes are public, so you need a list. And you’d better used one that is public and well-maintained.
just stumped upon this question and decided to write the following function.
Example Input -> Output:
http://example.com -> http://example.com
http://www.example.com -> http://example.com
ftp://www.a.example.com -> ftp://example.com
SFTP://www.a.example.com -> SFTP://example.com
http://www.a.b.example.com -> http://example.com
http://www.a.c.d.example.com -> http://example.com
http://example.com/ -> http://example.com/
https://example.com/aaa -> http://example.com/aaa
http://www.example.com/aa/bb../d -> http://example.com/aa/bb../d
FILE://www.a.example.com/ddd/dd/../ff -> FILE://example.com/ddd/dd/../ff
HTTPS://www.a.b.example.com/index.html?param=value -> HTTPS://example.com/index.html?param=value
http://www.a.c.d.example.com/#yeah../..! -> http://lmao.com/#yeah../..!
Same goes for second level domains
http://some.thing.co.uk/?ke - http://thing.co.uk/?ke
something.co.uk/?ke - something.co.uk/?ke
www.something.co.uk/?ke - something.co.uk/?ke
www.something.co.uk - something.co.uk
https://www.something.co.uk - https://something.co.uk
Code:
public static String removeSubdomains(String url, ArrayList<String> secondLevelDomains) {
// We need our URL in three parts, protocol - domain - path
String protocol= getProtocol(url);
url = url.substring(protocol.length());
String urlDomain=url;
String path="";
if(urlDomain.contains("/")) {
int slashPos = urlDomain.indexOf("/");
path=urlDomain.substring(slashPos);
urlDomain=urlDomain.substring(0, slashPos);
}
// Done, now let us count the dots . .
int dotCount = Strng.countOccurrences(urlDomain, ".");
// example.com <-- nothing to cut
if(dotCount==1){
return protocol+url;
}
int dotOffset=2; // subdomain.example.com <-- default case, we want to remove everything before the 2nd last dot
// however, somebody had the glorious idea, to have second level domains, such as co.uk
for (String secondLevelDomain : secondLevelDomains) {
// we need to check if our domain ends with a second level domain
// example: something.co.uk we don't want to cut away "something", since it isn't a subdomain, but the actual domain
if(urlDomain.endsWith(secondLevelDomain)) {
// we increase the dot offset with the amount of dots in the second level domain (co.uk = +1)
dotOffset += Strng.countOccurrences(secondLevelDomain, ".");
break;
}
}
// if we have something.co.uk, we have a offset of 3, but only 2 dots, hence nothing to remove
if(dotOffset>dotCount) {
return protocol+urlDomain+path;
}
// if we have sub.something.co.uk, we have a offset of 3 and 3 dots, so we remove "sub"
int pos = Strng.nthLastIndexOf(dotOffset, ".", urlDomain)+1;
urlDomain = urlDomain.substring(pos);
return protocol+urlDomain+path;
}
public static String getProtocol(String url) {
String containsProtocolPattern = "^([a-zA-Z]*:\\/\\/)|^(\\/\\/)";
Pattern pattern = Pattern.compile(containsProtocolPattern);
Matcher m = pattern.matcher(url);
if (m.find()) {
return m.group();
}
return "";
}
public static ArrayList<String> getPublicSuffixList(boolean loadFromPublicSufficOrg) {
ArrayList<String> secondLevelDomains = new ArrayList<String>();
if(!loadFromPublicSufficOrg) {
secondLevelDomains.add("co.uk");secondLevelDomains.add("co.at");secondLevelDomains.add("or.at");secondLevelDomains.add("ac.at");secondLevelDomains.add("gv.at");secondLevelDomains.add("ac.at");secondLevelDomains.add("ac.uk");secondLevelDomains.add("gov.uk");secondLevelDomains.add("ltd.uk");secondLevelDomains.add("fed.us");secondLevelDomains.add("isa.us");secondLevelDomains.add("nsn.us");secondLevelDomains.add("dni.us");secondLevelDomains.add("ac.ru");secondLevelDomains.add("com.ru");secondLevelDomains.add("edu.ru");secondLevelDomains.add("gov.ru");secondLevelDomains.add("int.ru");secondLevelDomains.add("mil.ru");secondLevelDomains.add("net.ru");secondLevelDomains.add("org.ru");secondLevelDomains.add("pp.ru");secondLevelDomains.add("com.au");secondLevelDomains.add("net.au");secondLevelDomains.add("org.au");secondLevelDomains.add("edu.au");secondLevelDomains.add("gov.au");
}
try {
String a = URLHelpers.getHTTP("https://publicsuffix.org/list/public_suffix_list.dat", false, true);
Scanner scanner = new Scanner(a);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(!line.startsWith("//") && !line.startsWith("*") && line.contains(".")) {
secondLevelDomains.add(line);
}
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
return secondLevelDomains;
}

Android / Java: Check if url is valid youtube url

I want to check if an url is valid youtube url so that I can shown in view otherwise I will hide the view.
Is there any regular expression in Java that can help me to check if url is valid. Currently I am using this regex but I guess it's not the one I want:
String youTubeURl = "https://www.youtube.com/watch?v=Btr8uOU0BkI";
String pattern = "https?:\\/\\/(?:[0-9A-Z-]+\\.)?(?:youtu\\.be\\/|youtube\\.com\\S*[^\\w\\-\\s])([\\w\\-]{11})(?=[^\\w\\-]|$)(?![?=&+%\\w]*(?:['\"][^<>]*>|<\\/a>))[?=&+%\\w]*";
if (!youTubeURl.isEmpty() && youTubeURl.matches(pattern)) {
/// Valid youtube URL
}
else{
// Not Valid youtube URL
}
This works for me.
public static boolean isYoutubeUrl(String youTubeURl)
{
boolean success;
String pattern = "^(http(s)?:\\/\\/)?((w){3}.)?youtu(be|.be)?(\\.com)?\\/.+";
if (!youTubeURl.isEmpty() && youTubeURl.matches(pattern))
{
success = true;
}
else
{
// Not Valid youtube URL
success = false;
}
return success;
}
If you want to retrieve the Youtube videoId you can use the following function.
public static String getVideoIdFromYoutubeUrl(String youtubeUrl)
{
/*
Possibile Youtube urls.
http://www.youtube.com/watch?v=WK0YhfKqdaI
http://www.youtube.com/embed/WK0YhfKqdaI
http://www.youtube.com/v/WK0YhfKqdaI
http://www.youtube-nocookie.com/v/WK0YhfKqdaI?version=3&hl=en_US&rel=0
http://www.youtube.com/watch?v=WK0YhfKqdaI
http://www.youtube.com/watch?feature=player_embedded&v=WK0YhfKqdaI
http://www.youtube.com/e/WK0YhfKqdaI
http://youtu.be/WK0YhfKqdaI
*/
String pattern = "(?<=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]*";
Pattern compiledPattern = Pattern.compile(pattern);
//url is youtube url for which you want to extract the id.
Matcher matcher = compiledPattern.matcher(youtubeUrl);
if (matcher.find()) {
return matcher.group();
}
return null;
}
You should use
Patterns.WEB_URL.matcher(youTubeURl).matches()
It will return True if URL is valid and false if URL is invalid.
Use android.webkit.URLUtil.isValidUrl(java.lang.String) to check if url is valid. And then you can check if url contains Youtube string.
Like
private boolean isValidUrl(String url) {
if (url == null) {
return false;
}
if (URLUtil.isValidUrl(url)) {
// Check host of url if youtube exists
Uri uri = Uri.parse(url);
if ("www.youtube.com".equals(uri.getHost())) {
return true;
}
// Other way You can check into url also like
//if (url.startsWith("https://www.youtube.com/")) {
//return true;
//}
}
// In other any case
return false;
}
In order to achieve what you want you should use this Regex like so:
private static final Pattern youtubePattern = Pattern.compile("^(http(s)?:\/\/)?((w){3}.)?youtu(be|.be)?(\.com)?\/.+");
private boolean isValid = youtubePattern.matcher(youtubeUrl).matches();
where youtubeUrl can be any URL of the following list:
http://youtu.be/t-ZRX8984sc
http://youtube.com/watch?v=iwGFalTRHDA
http://www.youtube.com/watch?v=t-ZRX8984sc
http://www.youtube.com/watch?v=iwGFalTRHDA&feature=related
http://www.youtube.com/embed/watch?feature=player_embedded&v=r5nB9u4jjy4
https://www.youtube.com/channel/UCDZkgJZDyUnqwB070OyP72g
youtube.com/n17B_uFF4cA
youtube.com/iwGFalTRHDA
http://youtu.be/n17B_uFF4cA
https://youtube.com/iwGFalTRHDA
https://youtube.com/channel/UCDZkgJZDyUnqwB070OyP72g
This regex can match any types of URLs related to youtube.com
This doesn't check if URL is valid or not. It only checks for strings "youtube" & "youtu.be" in your URL. Following is the regex
String yourUrl = "https://youtu.be/Xh0-x1RFEOY";
yourUrl.matches(".*(youtube|youtu.be).*")
" .* " at beginning & end means that there could be anything on left & right of the expression(youtube & youtu.be) you are checking.
NOTE: This has nothing to do with the validity of the URL

Categories