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;
}
Related
hey I need a regex that removes the leadings zeros.
right now I am using this code . it does work it just doesn't keep the negative symbol.
String regex = "^+(?!$)";
String numbers = txaTexte.getText().replaceAll(regex, ")
after that I split numbers so it puts the numbers in a array.
input :
-0005
0003
-87
output :
-5
3
-87
I was also wondering what regex I could use to get this.
the words before the arrow are input and after is the output
the text is in french. And right now I am using this it works but not with the apostrophe.
String [] tab = txaTexte.getText().split("(?:(?<![a-zA-Z])'|'(?![a-zA-Z])|[^a-zA-Z'])+")
Un beau JOUR. —> Un/beau/JOUR
La boîte crânienne —> La/boîte/crânienne
C’était mieux aujourd’hui —> C’/était/mieux/aujourd’hui
qu’autrefois —> qu’/autrefois
D’hier jusqu’à demain! —> D’/hier/jusqu’/à/demain
Dans mon sous-sol—> Dans/mon/sous-sol
You might capture an optional hyphen, then match 1+ more times a zero and 1 capture 1 or more digits in group 2 starting with a digit 1-9
^(-?)0+([1-9]\d*)$
^ Start of string
(-?) Capture group 1, match optional hyphen
0+ Match 0+ zeroes
([1-9]\d*) Capture group 2, match 1+ digits starting with a digit 1-9
$ End of string
See a regex demo.
In the replacement use group 1 and group 2.
String regex = "^(-?)0+([1-9]\\d*)$";
String text = "-0005";
String numbers = txaTexte.getText().replaceAll(regex, "$1$2");
Here is one way. This preserves the sign.
capture the optional sign.
check for 0 or more leading zeros
followed by 1 or more digits.
String regex = "^([+-])?0*(\\d+)";
String [] data = {"-1415", "+2924", "-0000123", "000322", "+000023"};
for (String num : data) {
String after = num.replaceAll(regex, "$1$2");
System.out.printf("%8s --> %s%n", num , after);
}
prints
-1415 --> -1415
+2924 --> +2924
-0000123 --> -123
000322 --> 322
+000023 --> +23
If you want to keep -000, 000, +0000 etc. as just 0, try this regex:
`^[-+]?0*(0)$|^([-+])?0*(\d+)$`
Break down:
^...$ means the entire string should match (^ is the start of the string, $ is the end)
...|... is an alternative
[-+] is a character class that contains only the plus and minus characters. Note that - has a special meaning ("range") in character classes if it's not the first or last character
(...) is a capturing group which can be referenced in the replacement string by $number where number is the 1-based and 1-digit position of the group within the regex (the first group to start is no. 1 etc.)
?, * and + are quantifiers when used outside character classes meaning "0 or 1 occurence" (?), "any number of occurences, including none" (*) and "at least one occurence" (+)
^[-+]?0*(0)$ thus means: the entire string must be an optional sign, followed by any number of zeros and ending with a single zero which is captured as group 1.
alternatively ^([-+])?0*(\d+)$ means the entire string must be an optional sign which is captured as group 2, followed by any number of zeros and ending in at least one digit which is captured as group 3.
This regex can then be used with String.replaceAll(regex, "$1$2$3") in order to keep only the single 0 from group 1 or the optional sign and the number without leading zeros from groups 2 and 3. Any empty groups will result empty strings, that's why this works.
However, regular expressions can be slow, especially if you have to process a lot of strings.
One thing to improve this would be to compile the pattern only once:
//compile the pattern once and reuse it
Pattern p = Pattern.compile("^[+-]?0*(0)$|^([+-])?0*(\\d+)$");
//build a matcher from the pattern and the input string, and do the replacement
String number = p.matcher(txaTexte.getText()).replaceAll("$1$2$3");
If you're working on a large number of strings (> 10000) you might want to use some specialized plain parsing without regex. Consider something like this, which on my machine is about 10x faster than the regex approach with reused pattern:
public static String stripLeadingZeros(String s) {
//nothing to do, return the string as is
if( s == null || s.isEmpty() ) {
return s;
}
char[] chars = s.toCharArray();
int usedChars = 0;
//check if the first character is the sign
boolean hasSign = false;
if(chars[0] == '-' || chars[0] == '+') {
hasSign = true;
usedChars++;
//special case: just a sign
if(chars.length == 1) {
return s;
}
}
//process the rest of the characters
boolean stripZeros = true;
for( int i = usedChars; i < chars.length; i++) {
//not a digit, this isn't a simple integer, stop processing and keep the original string
if( chars[i] < '0' || chars[i] > '9') {
return s;
}
//are we still in zero-stripping mode
if( stripZeros) {
if( chars[i] == '0') {
continue; //check next char
}
//we've found a non-zero char, keep it and end zero-stripping mode
if(chars[i] >= '1' && chars[i] <= '9') {
stripZeros = false;
}
}
//since we are ignoring leading zeros, we just move all digits of the actual number to the left
chars[usedChars++] = chars[i];
}
//handle special case of number 0 (with optional sign)
if( usedChars == (hasSign ? 1 : 0)) {
chars[0] = '0';
usedChars = 1;
}
return new String(chars,0, usedChars);
}
Im trying to figure out how this validate phone number to my android works.
I have add the code and whant to validate 46123456789 but the last number (9) doesent add to the phone number.
This i use:
/**
* #param phone
* #return The number which satisfies the above criteria, is a valid mobile Number.
* The first digit should contain number between 0 to 9.
* The rest 9 digit can contain any number between 0 to 9.
* The mobile number can have 11 digits also by including 0 at the starting.
* The mobile number can be of 12 digits also by including 46 at the starting
*/
public static boolean isValidPhoneNumber(String phone) {
phone = trimPhoneNumber(phone);
// The given argument to compile() method
// is regular expression. With the help of
// regular expression we can validate mobile
// number.
// 1) Begins with 0 or 46
// 2) Then contains 6 or 7 or 8 or 9.
// 3) Then contains 9 digits
Pattern p = Pattern.compile("(0/46)?[0-9][0-10]{9}");
// Pattern class contains matcher() method
// to find matching between given number
// and regular expression
Matcher m = p.matcher(phone);
return (m.find() && m.group().equals(phone));
}
public static String trimPhoneNumber(String phone) {
if (TextUtils.isEmpty(phone)) {
return phone;
} else {
try {
phone = phone.replace("+46", "");
phone = phone.replaceAll("[^0-9]", "");//replace all except 0-9
return phone;
} catch (Exception e) {
e.printStackTrace();
return phone;
}
}
}
Am i missing something
Use this pattern:
^\s*(?:(?:\+?46)|0)(?:\d){9,10}\s*$
^ at start and $ at end ensure pattern matches the whole input
\s* trim any space or tab
\d capture any digit
(?:\d){9,10} means the pattern (?:\d) should be repeated 9 to 10 times.
``
Pattern start with (+46 or 46) or 0 follow by 9 or 10 digit.
If it could contain - or space between numbers, use this:
^\s*(?:(?:\+?46)|0)(?:[- ]*\d){9,10}\s*$
You could test regex here
I need to do a check for a 5-digit number using regex. Check condition: 1. There should be no more than 2 repeating digits (type 11234). 2. There should be no sequence 12345 or 54321.
I am trying to do this:
var PASSWORD_PATTERN = "^(?=[\\\\D]*\\\\d)(?!.*(\\\\d)\\\\1)(?!.*\\\\2{3,}){5,}.*$",
But checking for 12345 or 54321 doesn't work.
You can assert for not 3 of the same digits, and assert not 12345 and 54321.
Note to double escape the backslash in Java \\d.
^(?!\d*(\d)\d*\1\d*\1)(?!12345)(?!54321)\d{5}$
The pattern matches:
^ Start of string
(?!\d*(\d)\d*\1\d*\1) Negative lookahead, do not match 3 times the same digits using 2 backreferences \1
(?!12345) Assert not 12345
(?!54321) Assert not 54322
\d{5} Match 5 digits
$ End of string
Regex demo
Or fail the match immediately, if the string does not consists of 5 digits, and match 1+ digits if all the assertions succeed.
^(?=\d{5}$)(?!\d*(\d)\d*\1\d*\1)(?!12345)(?!54321)\d+$
Regex demo
If you don't want to match ascending and descending sequences for digits 0-9, you might either manually check the string for each hardcoded sequence, or generate the sequences and add them to a list.
Then you can check if the sequence of 5 digits is in the list, and remove the exact check with the lookarounds from the pattern.
List<String> sequences = new ArrayList<>();
for (int i = 0; i < 10; i++) {
StringBuilder sequence = new StringBuilder();
int last = i;
for (int j = 0; j < 5; j++) {
++last;
if (last > 9) last = 0;
sequence.append(last);
}
sequences.add(sequence.toString());
sequences.add(sequence.reverse().toString());
}
String[] strings = {"12345", "54321", "34567", "90123", "112341", "12356", "00132"};
for (String s : strings) {
if ((!sequences.contains(s)) && s.matches("^(?=\\d{5}$)(?!\\d*(\\d)\\d*\\1\\d*\\1)\\d+$")) {
System.out.printf("%s is not a sequence and does not contain 3 of the same digits\n", s);
}
}
Output
12356 is not a sequence and does not contain 3 of the same digits
00132 is not a sequence and does not contain 3 of the same digits
Java demo
I would like to mask the last 4 digits of the identity number (hkid)
A123456(7) -> A123***(*)
I can do this by below:
hkid.replaceAll("\\d{3}\\(\\d\\)", "***(*)")
However, can my regular expression really can match the last 4 digit and replace by "*"?
hkid.replaceAll(regex, "*")
Please help, thanks.
Jessie
Personally, I wouldn't do it with regular expressions:
char[] cs = hkid.toCharArray();
for (int i = cs.length - 1, d = 0; i >= 0 && d < 4; --i) {
if (Character.isDigit(cs[i])) {
cs[i] = '*';
++d;
}
}
String masked = new String(cs);
This goes from the end of the string, looking for digit characters, which it replaces with a *. Once it's found 4 (or reaches the start of the string), it stops iterating, and builds a new string.
While I agree that a non-regex solution is probably the simplest and fastest, here's a regex to catch the last 4 digits independent if there is a grouping ot not: \d(?=(?:\D*\d){0,3}\D*$)
This expression is meant to match any digit that is followed by 0 to 3 digits before hitting the end of the input.
A short breakdown of the expression:
\d matches a single digit
\D matches a single non-digit
(?=...) is a positive look-ahead that contributes to the match but isn't consumed
(?:...){0,3} is a non-capturing group with a quantity of 0 to 3 occurences given.
$ matches the end of the input
So you could read the expression as follows: "match a single digit if it is followed by a sequence of 0 to 3 times any number of non-digits which are followed by a single digit and that sequence is followed by any number of non-digits and the end of the input" (sounds complicated, no?).
Some results when using input.replaceAll( "\\d(?=(?:\\D*\\d){0,3}\\D*$)", "*" ):
input = "A1234567" -> output = "A123****"
input = "A123456(7)" -> output = "A123***(*)"
input = "A12345(67)" -> output = "A123**(**)"
input = "A1(234567)" -> output = "A1(23****)"
input = "A1234B567" -> output = "A123*B***"
As you can see in the last example the expression will match digits only. If you want to match letters as well either replace \d and \D with \w and \W (note that \w matches underscores as well) or use custom character classes, e.g. [02468] and [^02468] to match even digits only.
I want to check if a userInput is free from special characters, here is my code:
public class ValidateHelper {
public boolean userInputContainsNoSpecialCharacters(String input){
Pattern p = Pattern.compile("[a-zA-Z_0-9 ]");
Matcher m = p.matcher(input);
boolean b = m.matches();
if (b)
return true;
else
return false;
}
}
This works if I type one character in a textfield -> "a" in the textfield -> the method returns true
"ab" in the textfield -> method returns false.
can somebody help please?
beste regards Daniel
Pattern p = Pattern.compile("[a-zA-Z_0-9 ]+");
Change "[a-zA-Z_0-9 ]" to "[a-zA-Z_0-9 ]+"
The + matches "one or more" of that group.
That is because you are using the character class []. If you would like to capture a limited amount, any amount or a range of characters you need to modify it.
[a-zA-Z_0-9 ]+ //1 or more characters
[a-zA-Z_0-9 ]{1,5} //1 - 5 characters
You should use the following regex:
[A-Za-z0-9]+
change your pattern from [a-zA-Z_0-9 ] to ^[a-zA-Z_0-9 ]*$ (for 0 or more valid characters) or ^[a-zA-Z_0-9 ]+$ if you want to ensure they enter a value
A + indicates 1 or more repetitions.
A * indicates 0 or more repetitions.
The ^ and $ denote the start end of the line respectively.