Allow any digit in a string other than 9 and 16 digits - java

^(?![\\s\\S]*(\\d{16})|[\\s\\S]*(\\d{9}))[\\s\\S]*
The above regex does not allow a number greater than 10 digits in the string.
Example, if user enters test 1234567891. The text is a valid text. We should allow user to enter this text.
The user should only not enter a 9 digit number or a 16 digit number.
Example, test 123456789 should be invalid. How to modify the regex.

Is this requirement best served by a regexp ? I think it would be much more readable to check the string length, and if you have a number.
Some people, when confronted with a problem, think "I know, I'll use
regular expressions." Now they have two problems.
and see here.

Don't use a regex for this kind of check. Java has .length() on strings:
private static final Pattern DIGITS = "\\d+";
public boolean inputOK(String input)
{
Matcher m = DIGITS.matcher(input);
int len;
while (m.find()) {
len = m.group().length();
if (len == 9 || len == 16)
return false;
}
return true;
}

Related

Regular expressions (denominator of a fraction)

Soo i think i already solved it, what i did:
String pattern = "(<=|>=)\\s{0,2}((+]\\s{0,2})?(\\d+\\s{0,2}[/]\\s{0,2}(\\d{2,}|[1-9])\\s{0,2}|\\d+[.]\\d{1,2}|\\d+))\\s{0,2}";
The pattern had something wrong, i have corrected it above and now it works :)
I have an inequation that may containing >= or <=, some white spaces and a number. That number might be an integer, a decimal number with 2 decimal places or a fraction and I want to retrieve the number on the 2nd member of the inequation with the "Matcher". Example:
4x1 + 6x2 <= 40/3
I've tried to construct such a pattern and I was able to find it. But then I've remembered that a fraction cannot be divided by zero so I want to check that aswell. For that I have used the following code:
String inequation = "4x1 + 6x2 <= 40/3";
String pattern = "(<=|>=)\\s{0,2}((+]\\s{0,2})?(\\d+\\s{0,2}[/]\\s{0,2}(\\d{2,}|[1-9])\\s{0,2}\\d+|\\d+[.]\\d{1,2}|\\d+))\\s{0,2}";
Pattern ptrn = Pattern.compile(pattern);
Matcher match = ptrn.matcher(inequation);
if(match.find()){
String fraction = match.group(2);
System.out.println(fraction);
} else {
System.out.println("NO MATCH");
}
But it's not working as expected. If it has at least 2 digits on the denominator it returns correctly (e.g. 40/32). But if it only has 1 digit it only returns the integer part (e.g. 40).
Anyway to solve this?
Which expression should I use?
Do you just want the number after the inequality sign? Then do:
Matcher m = Pattern.compile("[<>]=?\\s*(.+?)\\s*$").matcher(string);
String number = m.find() ? m.group(1) : null;
You could try using debuggex to build regular expressions. It shows you a nice diagram of your expression and you can test your inputs as well.
Java implementation (validates that the numerator is non-zero.):
Matcher m = Pattern.compile("[<>]=?\\s{0,2}([0-9]*(/[1-9][0-9]*)?)$").matcher("4x1 + 6x2 <= 40/3");
if (m.find()) {
System.out.println(m.group(1));
}
You need an '$' at the end of your expression, so that it tries to match the entire inequality.

Java check Phone number and matches

i want to check below phone number with matches, phone number conditions :
start with 0 or 9
content must be between 0 and 9
phone number must be 10 character
I tried:
String mobile_number = "9371236569";
if(!TextUtils.isEmpty(mobile_number) &&
mobile_number.matches("^[0][9][0-9]{10}$")) {
}
For number 9371236569 dont work my code and return false,
[ ] Matches any single character in brackets except range with -.
mobile_number.matches("^[09][0-9]{9}$")
^[09] start with eighter 0 or 9.
[0-9]{9} rest 9 digits raging from 0-9.
Use this regex:
"^(0|9)[0-9]{9}$"
Explanation:
^ match beginning of the string
(0|9) match one digit either a 0 or a 9
[0-9]{9} match 9 digits in the range of 0-9
$ match end of the string
public static boolean validateMobile(String moblieNumber) {
boolean check;
Pattern p;
Matcher m;
String MobilePattern = "[0-9]{10}";
p = Pattern.compile(MobilePattern);
m = p.matcher(moblieNumber);
check = m.matches();
return check;
}

Regex for password matching

I have searched the site and not finding exactly what I am looking for.
Password Criteria:
Must be 6 characters, 50 max
Must include 1 alpha character
Must include 1 numeric or special character
Here is what I have in java:
public static Pattern p = Pattern.compile(
"((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])|(?=.*[\\d~!##$%^&*\\(\\)_+\\{\\}\\[\\]\\?<>|_]).{6,50})"
);
The problem is that a password of 1234567 is matching(it is valid) which it should not be.
Any help would be great.
I wouldn't try to use a single regular expression to do that. Regular expressions tend not to perform well when they get long and complicated.
boolean valid(String password){
return password != null &&
password.length() >= 6 &&
password.length() <= 50 &&
password.matches(".*[A-Za-z].*") &&
password.matches(".*[0-9\\~\\!\\#\\#\\$\\%\\^\\&\\*\\(\\)_+\\{\\}\\[\\]\\?<>|_].*");
}
Make sure you use Matcher.matches() method, which assert that the whole string matches the pattern.
Your current regex:
"((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])|(?=.*[\\d~!##$%^&*\\(\\)_+\\{\\}\\[\\]\\?<>|_]).{6,50})"
means:
The string must contain at least a digit (?=.*\\d), a lower case English alphabet (?=.*[a-z]), and an upper case character (?=.*[A-Z])
OR | The string must contain at least 1 character which may be digit or special character (?=.*[\\d~!##$%^&*\\(\\)_+\\{\\}\\[\\]\\?<>|_])
Either conditions above holds true, and the string must be between 6 to 50 characters long, and does not contain any line separator.
The correct regex is:
"(?=.*[a-zA-Z])(?=.*[\\d~!##$%^&*()_+{}\\[\\]?<>|]).{6,50}"
This will check:
The string must contain an English alphabet character (either upper case or lower case) (?=.*[a-zA-Z]), and a character which can be either a digit or a special character (?=.*[\\d~!##$%^&*()_+{}\\[\\]?<>|])
The string must be between 6 and 50 characters, and does not contain any line separator.
Note that I removed escaping for most characters, except for [], since {}?() loses their special meaning inside character class.
A regular expression can only match languages which can be expressed as a deterministic finite automaton, i.e. which doesn't require memory. Since you have to count special and alpha characters, this does require memory, so you're not going to be able to do this in a DFA. Your rules are simple enough, though that you could just scan the password, determine its length and ensure that the required characters are available.
I'd suggest you to separate characters and length validation:
boolean checkPassword(String password) {
return password.length() >= 6 && password.length() <= 50 && Pattern.compile("\\d|\\w").matcher(password).find();
}
I would suggest splitting into separate regular expressions
$re_numbers = "/[0-9]/";
$re_letters = "/[a-zA-Z]/";
both of them must match and the length is tested separately, too.
The code looks quite cleaner then and is easier to understand/change.
This way too complex for such a simple task:
Validate length using String#length()
password.length() >= 6 && password.length() <= 50
Validate each group using Matcher#find()
Pattern alpha = Pattern.compile("[a-zA-Z]");
boolean hasAlpha = alpha.matcher(password).find();
Pattern digit = Pattern.compile("\d");
boolean hasDigit = digit.matcher(password).find();
Pattern special = Pattern.compile("[\\~\\!\\#\\#\\$\\%\\^\\&\\*\\(\\)_+\\{\\}\\[\\]\\?<>|_]");
boolean hasSpecial = special.matcher(password).find();

Java, Regex match first 10 digits in String, disregard leading zeros

I am interested to extract the first 10 digits if exists from a long string while disregarding the leading zeros. Additionally if there are only zeroes, return only 1 zero, if there no numbers, return empty string. I wish to match it in a single find.
For example:
"abcd00111.g2012asd" should match to "1112012"
"aktr0011122222222222ddd" should match to "1112222222"
"asdas000000asdasds0000" should match to "0"
"adsads.cxzv.;asdasd" should match to ""
Here is what I have tried so far: Ideone Demo - code
Pattern p = Pattern.compile("[1-9]{1}+[0-9]{9}");
Matcher m = p.matcher(str);
if (m.find()) {
String match = m.group();
System.out.println(match);
}
The problem is that this regex require 9 sequential digits after the first non zero, and I need any 9 digits (possible non digit chars in between).
Notice that in the code I have if (m.find()) instead of while (m.find()) because I wish to find the match in single run.
UPDATE
base on the comments i understood that it is not possible with regex to do it in single run.
I would like an answer not have to be regex based but most efficient since i will execute this method many times.
In general case, it is not possible to do it with a single find. You can do it if you know the maximum number of contiguous sequence of digits, but if that is not known, then it is not possible, at least at the level of support of Java Pattern class. I was wrong about this. Kobi's comment shows that it is possible with a single regex. I will reproduce the comment here:
Oh, and it is sort of possible with a regex, by capturing each of the 10 digits, something like: ^[\D0]*(\d)\D*(?:(\d)\D*(?:(\d)\D*(?:(\d)\D*(?#{6 more times}))?)?)?, but it is really ugly, and doesn't scale well.
You still need to concatenate the groups, though. The logic in the regex at the beginning is quite nice: due to the greedy property, it will search for the first non-zero digit that are after all the leading zero if any, or it will take the last 0 if there is no non-zero digit.
If you throw the talk about efficiency out of the door, and you want short code:
String digitOnly = str.replaceAll("\\D+", "");
String noLeadingZero = digitOnly.replaceFirst("^0+", "");
String result = digitOnly.isEmpty() ? "" :
noLeadingZero.isEmpty() ? "0" :
noLeadingZero.substring(0, Math.min(noLeadingZero.length(), 10));
Frankly, a loop through the string, with a StringBuilder is good enough, and it should be faster than regex solution.
StringBuilder output = new StringBuilder();
boolean hasDigit = false;
boolean leadingZero = true;
for (int i = 0; i < str.length() && output.length() < 10; i++) {
char currChar = str.charAt(i);
if ('0' <= currChar && currChar <= '9') {
hasDigit = true;
if (currChar != '0') {
output.append(currChar);
leadingZero = false;
} else if (!leadingZero) { // currChar == 0
output.append(currChar);
} // Ignore leading zero
}
}
String result = !hasDigit ? "" :
output.length() == 0 ? "0" :
output.toString();
Performance testing code. Note that you should adjust the parameters to make it resemble actual input so that you get a good approximation. I doubt looping method is slower than anything involving regex; however, the difference is only significant on large scale.
String test = "sdfsd0000234.432004gr23.022";
StringBuilder sb = new StringBuilder();
for(int i=0;i<test.length();i++) {
if(Character.isDigit(test.charAt(i)))
sb = sb.append(test.charAt(i));
}
String result = sb.toString();
result = result.replaceFirst("^0*", ""); //Remove leading zeros
System.out.println(result); //Will print 23443200423022

java check the first and last char are uppercase

I am trying to achieve this.
I have a string of 9char (always the same). But i also know that the first and last char is always a aplhabetic, it must be. the rest in the middle are numbers. How to check for that.
I got this logic so far, syntax is my problem
string samplestring;
samplestring = a1234567B
If(samplestring.length() == 9 && samplestring.substring(0,1).uppercase && samplestring.substring(8,9) && samplestring.THE REST OF THE CHAR IN THE MIDDLE ARE DIGITS)
{
println("yes this is correct");
}
else
{
println("retype");
}
Please dont mind about the simple english just want to know the syntax but the logic is there i hope..
Also can please show me those lowercase ones how to convert to uppercase?
A regular expression would be suitable:
String s = new String("A2345678Z");
if (s.matches("[A-Z][0-9]{7}[A-Z]")))
{
}
Regular expression explained:
[A-Z] means any uppercase letter
[0-9]{7} means 7 digits
Pattern p = Pattern.compile("^[A-Za-z]\\d+[A-Za-z]$");
Matcher m = p.match("A1234567B");
if (m.matches()) {
//
}
Edit:
If there are always seven digits, you can replace the \\d+ with \\d{7}
String str="A12345678B";
char first = str.charAt(0);
char second = str.charAt(str.length()-1);
if(Character.isUpperCase(first)&& Character.isUpperCase(second)){
//do something
}

Categories