Regular expression for phone number starting with '00' or '+' - java

I've got a regex problem: I'm trying to force a phone number beginning with either "00" or "+" but my attempt doesn't work.
String PHONE_PATTERN = "^[(00)|(+)]{1}[0-9\\s.\\/-]{6,20}$";
It still allows for example "0123-45678". What am i doing wrong?

Inside character class every character is matched literally, which means [(00)|(+)] will match a 0 or + or | or ( or )
Use this regex:
String PHONE_PATTERN = "^(?:00|\\+)[0-9\\s.\\/-]{6,20}$";

if you have removed spaces, hyphens and whatever from the number, and you want to catch either +xxnnnnnnnn or 00xxnnnnnnnn where xx is the country code of course and n is the 9 digit number OR 0nnnnnnnnn where a non international number starting with a zero is followed by 9 digits then try this regex
String PHONE_PATTERN = "^(?:(?:00|\+)\d{2}|0)[1-9](?:\d{8})$"

Related

Remove Spaces and Special Characters (between Numbers only) in a string

I am novice in RegEx. I am trying to strip all whitespaces and special characters between numbers in a string. Please know that string may contain other characters with numbers.
For Example take this string,
String s1 = "This is Sample AmericanExp Card Number 3400 1000 2000 009";
What I am trying is :-
String s1 = "This is Sample AmericanExp Card Number 3400 1000 2000 009";
String regExp = "[^\\w]+";
String replacement = "";
String changed= s1.replaceAll(regExp, replacement);
System..out.println("changed->"+content);
Its giving output as ThisisSampleAmericanExpCardNumber340000000000009,
The Required output is "This is Sample AmericanExp Card Number 340010002000009".
Appreciate The Help and Please let me know the concept behind it.
EDIT:-
Now I am masking the card Number and Its Pin (PCI), So I have this formula
^((4\\d{3})|(5[1-5]\\d{2})|(6011))-?\\d{4}-?\\d{4}-?\\d{4}|3[4,7]\\d{13}$
Which Checks for some type of credit cards. I am modifying it to check for its PIN and CVV also.(Matching 4 and 6 digit numbers also)
Sample String = "Sample AmericanExp Card Number 3400 1000 2000 009 and PIN is 1234 , CVV = 654321"
I modified the formula as :
^((4\\d{3})|(5[1-5]\\d{2})|(6011))-?\\d{4}-?\\d{4}-?\\d{4}|3[47]\\d{13}$|^[0-9]{4}$|^[0-9]{6}$
Which Doesn't gives me the correct output (Matching 4 and 6 digit numbers also).
You may use
.replaceAll("(?<=\\d)[\\W_]+(?=\\d)", "")
Or, if you need to deal with Unicode strings:
.replaceAll("(?U)(?<=[0-9])[\\W_]+(?=[0-9])", "")
See the regex. Details:
(?<=\d) - a positive lookbehind that matches a position immediately preceded with a digit
[\W_]+ - one or more non-word or underscore characters
(?=\d) - a positive lookahead that matches a location immediately followed with a digit.
Note that the (?U), Pattern.UNICODE_CHARACTER_CLASS embedded option, will make \W Unicode aware and it will no longer match Cyrillic, etc. letters.
See the Java demo:
String s1 = "This is Sample AmericanExp Card Number 3400 1000 2000 009";
System.out.println("changed -> " + s1.replaceAll("(?<=\\d)[\\W_]+(?=\\d)", ""));
// => changed -> This is Sample AmericanExp Card Number 340010002000009

How to extract specific substring from an expression in java

I have the following text:
Units Currently On Bed List
[total beds=0]
Number Of Beds Unit Interval Select All
The number after '=' is dynamic and subject to change. How can I extract the number in java using regex?
If you mean "number after = is dynamic and subject to change.", then for your example data you could for example capture the number in a group:
\[.+?=(\d+)\]
Match a \[
Match any character one or more times non greedy .+?
Match an equal sign =
Capture 1 or more digits (\d+)
Match a \]
Not sute using regex but this is one way :
int first = str.indexOf('=') +1;
int last = str.lastIndexOf(']');
String nbr = str.subString(first,last );
int number = Integer.parseInt(nbr);

Mask mobile number in Java [duplicate]

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.

Formatting numbers in a mathematical expression from String values in java

I know how to set thousands separator for numbers but i need to display numbers with thousands separator in mathematical expression from String values.
Basically, I want these results:
"123456 + 36514" becomes "123,456 + 36,514"
"12345678 + 36542 * 69541 / 987654" becomes "12,345,678 + 36,542 * 69,541 / 987,654"
and ...
You want to insert comma after a digit that is followed by an exact number of 3-digit blocks, so:
(?<=\d) Positive lookbehind: Match a digit
(?= Positive lookahead:
(?:\d{3})+ One or more sequences of 3 digits
\b Word-boundary, i.e. end of digit sequence
)
That will match the empty spaces where you want commas, so do a replaceAll():
str = str.replaceAll("(?<=\\d)(?=(?:\\d{3})+\\b)", ",");
See regex101 for demo.
I can provide you an algorithm rather giving the code:
Loop: String of repression one character at a time
{
If the current char is 0 to 9 append to tempNumber string
else
{
//by the time you reach this line the number is in the tempNumber string
Format the number stored in tempNumber // java.text.NumberFormat
append the formatted number in targetExpression string
append the current char to the targetExpression string
}
}

Regex to get first number in string with other characters

I'm new to regular expressions, and was wondering how I could get only the first number in a string like 100 2011-10-20 14:28:55. In this case, I'd want it to return 100, but the number could also be shorter or longer.
I was thinking about something like [0-9]+, but it takes every single number separately (100,2001,10,...)
Thank you.
/^[^\d]*(\d+)/
This will start at the beginning, skip any non-digits, and match the first sequence of digits it finds
EDIT:
this Regex will match the first group of numbers, but, as pointed out in other answers, parseInt is a better solution if you know the number is at the beginning of the string
Try this to match for first number in string (which can be not at the beginning of the string):
String s = "2011-10-20 525 14:28:55 10";
Pattern p = Pattern.compile("(^|\\s)([0-9]+)($|\\s)");
Matcher m = p.matcher(s);
if (m.find()) {
System.out.println(m.group(2));
}
Just
([0-9]+) .*
If you always have the space after the first number, this will work
Assuming there's always a space between the first two numbers, then
preg_match('/^(\d+)/', $number_string, $matches);
$number = $matches[1]; // 100
But for something like this, you'd be better off using simple string operations:
$space_pos = strpos($number_string, ' ');
$number = substr($number_string, 0, $space_pos);
Regexs are computationally expensive, and should be avoided if possible.
the below code would do the trick.
Integer num = Integer.parseInt("100 2011-10-20 14:28:55");
[0-9] means the numbers 0-9 can be used the + means 1 or more times. if you use [0-9]{3} will get you 3 numbers
Try ^(?'num'[0-9]+).*$ which forces it to start at the beginning, read a number, store it to 'num' and consume the remainder without binding.
This string extension works perfectly, even when string not starts with number.
return 1234 in each case - "1234asdfwewf", "%sdfsr1234" "## # 1234"
public static string GetFirstNumber(this string source)
{
if (string.IsNullOrEmpty(source) == false)
{
// take non digits from string start
string notNumber = new string(source.TakeWhile(c => Char.IsDigit(c) == false).ToArray());
if (string.IsNullOrEmpty(notNumber) == false)
{
//replace non digit chars from string start
source = source.Replace(notNumber, string.Empty);
}
//take digits from string start
source = new string(source.TakeWhile(char.IsDigit).ToArray());
}
return source;
}
NOTE: In Java, when you define the patterns as string literals, do not forget to use double backslashes to define a regex escaping backslash (\. = "\\.").
To get the number that appears at the start or beginning of a string you may consider using
^[0-9]*\.?[0-9]+ # Float or integer, leading digit may be missing (e.g, .35)
^-?[0-9]*\.?[0-9]+ # Optional - before number (e.g. -.55, -100)
^[-+]?[0-9]*\.?[0-9]+ # Optional + or - before number (e.g. -3.5, +30)
See this regex demo.
If you want to also match numbers with scientific notation at the start of the string, use
^[0-9]*\.?[0-9]+([eE][+-]?[0-9]+)? # Just number
^-?[0-9]*\.?[0-9]+([eE][+-]?[0-9]+)? # Number with an optional -
^[-+]?[0-9]*\.?[0-9]+([eE][+-]?[0-9]+)? # Number with an optional - or +
See this regex demo.
To make sure there is no other digit on the right, add a \b word boundary, or a (?!\d)
or (?!\.?\d) negative lookahead that will fail the match if there is any digit (or . and a digit) on the right.
public static void main(String []args){
Scanner s=new Scanner(System.in);
String str=s.nextLine();
Pattern p=Pattern.compile("[0-9]+");
Matcher m=p.matcher(str);
while(m.find()){
System.out.println(m.group()+" ");
}
\d+
\d stands for any decimal while + extends it to any other decimal coming directly after, until there is a non number character like a space or letter

Categories