Regular Expression not matched - android

I am trying to validate my string with the regular expression. Here is what I am trying to do
EditText serialText = (EditText) findViewById(R.id.pinText);
serialText.setVisibility(View.VISIBLE);
serialNumber = serialText.getText().toString();
I am storing the serial number in serialNumber
I have the following method to match the regular expression
boolean isRegularSerialNumber(String pinNumber) {
// regular expression to be matched against
String regularString = "[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}";
Pattern pattern = Pattern.compile(regularString);
Matcher matcher = pattern.matcher(pinNumber);
boolean isRegularSerialNumberValid ;
if (pinNumber.matches(regularString))
isRegularSerialNumberValid = true;
else
isRegularSerialNumberValid = false;
return isRegularSerialNumberValid;
}
But I am not able to match this.
Any answer for this? Hope Pattern and Matcher are the right one for this.
What I am trying to do is this, this matched serialNumber I am validating against serial number stored in the database. If match found, it returns success or else failure. And i have entered the exact serial number which is stored in the database but even then it returns failure.
I followed the method what #Stevehb said and i got the match true in that case.
This is how I am sending my data
parameter.add(new BasicNameValuePair("validate", serialNumber));
Breaking my head on this.

The built in String functions should work by themselves. isRegularSerialNumber() could just be
boolean isRegularSerialNumber(String pinNumber) {
String regularString = "[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}";
return pinNumber.matches(regularString);
}
This works for me when I tested 1234-5678-9012-1324 (true) and 12-1234-123-1324 (false).
Also, it looks like you're maybe grabbing the input string from serialText right after you make it visible. Could your problem be in grabbing the text before the user has made any input?

looks much alike .net regex code.
instead of
if (pinNumber.matches(regularString))
try
if (matcher.matches())

Related

How to validate an email address' specific domain?

I've seen solutions here to validate whether an email address is formatted correctly, however I would like to check if an email address uses a specific domain such as "#gmail.com". The example I am referring to which validates email address format in general is:
public final static boolean isValidEmail(CharSequence target) {
if (TextUtils.isEmpty(target)) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
You might use endsWith and use #gmail.com like:
"test#gmail.com".endsWith("#gmail.com")
Or use a regex like ^\S+#gmail\.com$
Details
^ Assert position at the start of the line
\S+ Match any non whitespace characters one or more times
#gmail\.com match #gmail.com
$ Assert position at the end of the line
For example
if ("test#gmail.com".matches("^\\S+#gmail\\.com$")) {
System.out.println("Match!");
}
Demo Java
You could make use of regex.
Pattern p = Pattern.compile(".*#gmail\.com");
Matcher m = p.matcher("hello#gmail.com");
boolean b = m.matches();
The simplest solution would be checking if the email contains the specified domain. Later you could add a regex or even a dictionary to store the different domains, instead of using one method for each individual domain.
private boolean isFromGmailDomain(String email, String domain)
{
return email.contains(domain);
}
You could make use of regex.
You can check regex https://www.regextester.com/94044
^[a-zA-Z0-9_.+-]+#(?:(?:[a-zA-Z0-9-]+.)?[a-zA-Z]+.)?(domain.in|domain2.com)

How to fetch multiple matched pattern from a single string

How can I get patterns using find() method and store the matched patterns in a arraylist
Input string: 9547235617/7865421341
I want to fetch both numbers and pass it in to an arrary list.
Current I am using the below pattern compile method to find the patterns as follows
Pattern number = Pattern.compile("^[789]\\d{9}$");
Matcher matcher = number.matcher(list_string);
if (!matcher.matches()) {
arraylist.add("No number available");
}
elseif (matcher.find()) {
arraylist.add(matcher.group());
}
Log.e("Arraylist value is","==>"+arraylist.tostring());
In this methods it always go the the first if condition and when a try to run the same string in other regex testing program on online examples it only matches the last number as pattern I don't have any idea what to do next hope some one can help
output: Arraylist value is ==>No number available
Note: I need to fetch both numbers and add it to array list.Currently I have used splits for special characters and store those splits in to array list but i want a method regarding regex pattern matching.
matches() will only return true if the full string is matched. find() will try to find the next occurrence within the substring that matches the regex.
Regex: (?<=^|\/)(?:\b[7-9]\d{9}\b)?
Java code:
String[] aStr = {"9547235617/7865421341", "6547235617/5865421341", "4547235617/9865421341"};
for(String str: aStr) {
Matcher matcher = Pattern.compile("(?<=^|\\/)(?:\\b[7-9]\\d{9}\\b)?").matcher(str);
while(matcher.find()){
if(matcher.group().equals("")) {
System.out.print("No number available" + "\n");
} else {
System.out.print(matcher.group() + "\n");
}
}
}
Output:
9547235617
7865421341
No number available
No number available
No number available
9865421341
Code demo

Finding Multiple Integers Inside A String Using Regex

I currently have this code below:
Pattern intsOnly = Pattern.compile("\\d+");
Matcher matcher = intsOnly.matcher(o1.getIngredients());
matcher.find();
String inputInt = matcher.group();
What currently happens is that using Regex, it finds the first integer inside a string and separates it so that I can carry out actions on it. The string that I am using to find integers inside of has many integers and I want them all separate. How can I tweak this code so that it also records the other integers from the string, not just the first one.
Thanks in advance!
In your posted code:
matcher.find();
String inputInt = matcher.group();
You are matching the whole string with a single call to find. And then assigning the first match of digits to your String inputInt. So for example, if you have the below string data, your return will only be 1.
1 egg, 2 bacon rashers, 3 potatoes
You should use a while loop to loop over your matches.
Pattern intsOnly = Pattern.compile("\\d+");
Matcher matcher = intsOnly.matcher(o1.getIngredients());
while (matcher.find()) {
System.out.println(matcher.group());
}

Does Android have a function to validate passwords?

I'm developing an Android app and one of my tasks is to check the strength of a password.
Are there any built-in functions for checking the strength of a password?
In order to answer the question, there is no Android function to do this, the closest and best way is to use regex as Mkyong suggested on his blog:
private Pattern pattern;
private Matcher matcher;
private static final String PASSWORD_PATTERN =
"((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%]).{6,20})";
public PasswordValidator(){
pattern = Pattern.compile(PASSWORD_PATTERN);
}
/**
* Validate password with regular expression
* #param password password for validation
* #return true valid password, false invalid password
*/
public boolean validate(final String password){
matcher = pattern.matcher(password);
return matcher.matches();
}
If you dont't want to use external libs.. you can check it yourself.. Something like this:
public void onSubmitClicked(View v)
{
String pass = passwordEditText.getText().toString();
if(TextUtils.isEmpty(pass) || pass.length < [YOUR MIN LENGTH])
{
passwordEditText.setError("You must more characters in your password");
return;
}
if(....){
// do other controls here
}
}
Sounds like you need an external library such as http://code.google.com/p/vt-middleware/wiki/vtpassword etc.
Or it is simple enough to code up something like checking how long it is, what characters it has etc and printing out different things based on that.
If say a user had a 10 length password and some upper case characters you could increment some password strength parameter based on this, rewarding more complex passwords. You can set teh thresholds yourself.

Android regexp HTML

I've got a HTML code stored in string and I want to extract all parts that match the pattern, which is:
<a href="http://abc.pl/(.*?)/(.*?)"><img src="(.*?)"
(.*?) stands for any string. I've tried dozens of combinations and couldn't get it working. Can somebody show me a sample code, which extracts all matched data from a String and store it in variables?
Thanks in advance
Here is a solution using JavaScript. I hope this helps.
First, we need a working pattern:
var pattern = '<a href="http://abc.pl/([^/"]+)/([^/"]*)".*?><img src="([^"]*)"';
Now, the problem is that in JavaScript there is no native method or function that retrieves both all matches and all submatches at once, whatever the regexp we use.
We can easily retrieve an array of all the full matches:
var re = new RegExp(pattern, "g");
var matches = yourHtmlString.match(re);
But we also want the submatches, right? In my humble opinion, the simplest way to achieve this is to apply the non-greedy version of the same regexp to each match we obtained (because only non-greedy regexes can return submatches):
var reNonGreedy = new RegExp(pattern);
var matchesAndSubmatches = [];
for(var i = 0; i < matches.length; i++) {
matchesAndSubmatches[i] = matches[i].match(reNonGreedy);
}
Each element of matchesAndSubmatches is now an array such that:
matchesAndSubmatches[n][0] is the n-th full match,
matchesAndSubmatches[n][1] is the first submatch of the n-th full match,
matchesAndSubmatches[n][2] is the second submatch of the n-th full match, and so on.
Well, here's the sample:
Pattern pattern = Pattern.compile("patternGoesHere");
Matcher matcher = pattern.matcher(textGoesHere);
while (matcher.find())
{
// You can access substring here via matcher.group(substringIndex) [note they are indexed from 1, not 0]
}

Categories

Resources