How to validate this using Regex C# - c#

I have a input which can be the following (Either one of these three):
1-8…in other words 1, 2,3,4,5,6,7,8
A-Z….in other words, A, B, C, D etc
01-98…in other words, 01,02,03,04 etc
I came up with this regex but it's not working not sure why:
#"[A-Z0-9][1-8]-
I am thinking to check for corner cases like just 0 and just 9 after regex check because regex check isn't validating this

Not sure I understand, but how about:
^(?:[A-Z]|[1-8]|0[1-9]|[1-8][0-9]|9[0-8])$
Explanation:
(?:...) is a group without capture.
| introduces an alternative
[A-Z] means one letter
[1-8] one digit between 1 and 8
0[1-9] a 0 followed by a digit between 1 and 9
[1-8][0-9] a digit between 1 and 8 followed by a digit between 1 and 9
9[0-8] 9 followed by a digit between 0 and 8
May be it is, depending on your real needs:
^(?:[A-Z]|[0-9]?[1-8])$

I think you may use this pattern
#"^([1-8A-Z]|0[1-9]|[1-9]{2})$"

What about ^([1-8]|([0-9][0-9])|[A-Z])$ ?
That will give a match for
A
8 (but not 9)
09

[1-8]{0,1}[A-Z]{0,1}\d{1,2}
matches all of the following
8A8 8B9 9 0 00

You can use following pattern:
^[1-8][A-Z](?:0[1-9]|[1-8][0-9]|9[0-8])$
^[1-8] - input should start with number 1-8
[A-Z] - then should be single letter A-Z
(0[1-9]|[1-8][0-9]|9[0-8])$ and it should end with two numbers which are 01-19 or 10-89 or 90-98
Test:
string pattern = #"^[1-8][A-Z](0[1-9]|[1-8][0-9]|9[0-8])$";
Regex regex = new Regex(pattern);
string[] valid = { "1A01", "8Z98" };
bool allMatch = valid.All(regex.IsMatch);
string[] invalid = { "0A01", "11A01", "1A1", "1A99", "1A00", "101", "1AA01" };
bool allNotMatch = !invalid.Any(regex.IsMatch);

Related

Search for 2 specific letters followed by 4 numbers Regex

I need to check if a string begins with 2 specific letters and then is followed by any 4 numbers.
the 2 letters are "BR" so BR1234 would be valid so would BR7412 for example.
what bit of code do I need to check that the string is a match with the Regex in C#?
the regex I have written is below, there is probably a more efficient way of writing this (I'm new to RegEx)
[B][R][0-9][0-9][0-9][0-9]
You can use this:
Regex regex = new Regex(#"^BR\d{4}");
^ defines the start of the string (so there should be no other characters before BR)
BR matches - well - BR
\d is a digit (0-9)
{4} says there must be exactly 4 of the previously mentioned group (\d)
You did not specify what is allowed to follow the four digits. If this should be the end of the string, add a $.
Usage in C#:
string matching = "BR1234";
string notMatching = "someOther";
Regex regex = new Regex(#"^BR\d{4}");
bool doesMatch = regex.IsMatch(matching); // true
doesMatch = regex.IsMatch(notMatching); // false;
BR\d{4}
Some text to make answer at least 30 characters long :)

Regex expression to replace colon grouped integers into years, months, and days and drop leading zeroes

I'm pretty bad at Regex (C#) with my attempts at doing the following giving non-sense results.
Given string: 058:09:07
where only the last two digits are guaranteed, I need the result of:
"58y 9m 7d"
The needed rules are:
The last two digits "07" are days group and always present. If "00", then only the last "0" is to be printed,
The group immediately to the left of "07" which ends with ":" signify the months and are only present if enough days are present to lead into months. Again, if "00", then only the last "0" is to be printed,
The group immediately to the left of "09:" which ends with ":" signify years and will only be present if more then 12 months are needed.
In each group a leading "0" will be dropped.
(This is the result of an age calculation where 058:09:07 means 58 years, 9 months, and 7 days old. The ":" (colon) always used to separate years from months from days).
Example:
058:09:07 --> 58y 9m 7d
01:00 --> 1m 0d
08:00:00 --> 8y 0m 0d
00 --> 0d
Any help is most appreciated.
Well, you can pretty much do this without regex.
var str = "058:09:07";
var integers = str.Split(':').Select(int.Parse).ToArray();
var result = "";
switch(integers.Length)
{
case 1:
result = string.Format("{0}d", integers[0]); break;
case 2:
result = string.Format("{0}m {1}d", integers[0], integers[1]); break;
case 3:
result = string.Format("{0}y {1}m {2}d", integers[0], integers[1], integers[2]); break;
}
If you want to use regex so bad, that it starts to hurt, you can use this one instead:
var integers = Regex.Matches(str, "\d+").Cast<Match>().Select(x=> int.Parse(x.Value)).ToArray();
But, its overhead, of course. You see, regex is not parsing language, its pattern matching language, and should be used as one. For example, for finding substrings in strings. If you can find final substrings simply by cutting it by char, why not to use it?
DISCLAIMER: I am posting this answer for the educational purposes. The easiest and most correct way in case the whole string represents the time span eocron06's answer is to be used.
The point here is that you have optional parts that go in a specific order. To match them all correctly you may use the following regex:
\b(?:(?:0*(?<h>\d+):)?0*(?<m>\d+):)?0*(?<d>\d+)\b
See the regex demo
Details:
\b - initial word boundary
(?: - start of a non-capturing optional group (see the ? at the end below)
(?:0*(?<h>\d+):)? - a nested non-capturing optional group that matches zero or more zeros (to trim this part from the start from zeros), then captures 1+ digits into Group "h" and matches a :
0*(?<m>\d+): - again, matches zero or more 0s, then captures one or more digits into Group "m"
)? - end of the first optional group
0*(?<d>\d+) - same as the first two above, but captures 1+ digits (days) into Group "d"
\b - trailing word boundary
See the C# demo where the final string is built upon analyzing which group is matched:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
var pattern = #"\b(?:(?:0*(?<h>\d+):)?0*(?<m>\d+):)?0*(?<d>\d+)\b";
var strs = new List<string>() {"07", "09:07", "058:09:07" };
foreach (var s in strs)
{
var result = Regex.Replace(s, pattern, m =>
m.Groups["h"].Success && m.Groups["m"].Success ?
string.Format("{0}h {1}m {2}d", m.Groups["h"].Value, m.Groups["m"].Value, m.Groups["d"].Value) :
m.Groups["m"].Success ?
string.Format("{0}m {1}d", m.Groups["m"].Value, m.Groups["d"].Value) :
string.Format("{0}d", m.Groups["d"].Value)
);
Console.WriteLine(result);
}
}
}

regex expression help needed

I was wondering if this was possible using Regex. I would like to exclude all letters (upper and lowercase) and the following 14 characters ! “ & ‘ * + , : ; < = > # _
The problem is the equal sign. In the string (which must either be 20 or 37 characters long) that I will be validating, that equal sign must either be in the 17th or 20th position because it is used as a separator in those positions. So it must check if that equal sign is anywhere other than in the 16th or 20th position (but not both). The following are some examples:
pass: 1234567890123456=12345678901234567890
pass: 1234567890123456789=12345678901234567
don't pass: 123456=890123456=12345678901234567
don't pass: 1234567890123456=12=45678901234567890
I am having a hard time with the part that I must allow the equal sign in those two positions and not sure if that's possible with Regex. Adding an if-statement would require substantial code change and regression testing because this function that stores this regex currently is used by many different plug-ins.
I'll go for
^([^a-zA-Z!"&'*+,:;<=>#_]{16}=[^a-zA-Z!"&'*+,:;<=>#_]+|[^a-zA-Z!"&'*+,:;<=>#_]{19}=[^a-zA-Z!"&'*+,:;<=>#_]*)$
Explanations :
1) Start with your allowed char :
^[^a-zA-Z!"&'*+,:;<=>#_]$
[^xxx] means all except xxx, where a-z is lower case letters A-Z upper case ones, and your others chars
2) Repeat it 16 times, then =, then others allowed chars ("allowed char" followed by '+' to tell that is repeated 1 to n times)
^[^a-zA-Z!"&'*+,:;<=>#_]{16}=[^a-zA-Z!"&'*+,:;<=>#_]+$
At this point you'll match your first case, when = is at position 17.
3) Your second case will be
^[^a-zA-Z!"&'*+,:;<=>#_]{19}=[^a-zA-Z!"&'*+,:;<=>#_]*$
with the last part followed by * instead of + to handle strings that are only 20 chars long and that ends with =
4) just use the (case1|case2) to handle both
^([^a-zA-Z!"&'*+,:;<=>#_]{16}=[^a-zA-Z!"&'*+,:;<=>#_]+|[^a-zA-Z!"&'*+,:;<=>#_]{19}=[^a-zA-Z!"&'*+,:;<=>#_]*)$
Tested OK with notepad++ and your examples
Edit to match exactly 20 or 37 chars
^([^a-zA-Z!"&'*+,:;<=>#_]{16}=[^a-zA-Z!"&'*+,:;<=>#_]{3}|[^a-zA-Z!"&'*+,:;<=>#_]{16}=[^a-zA-Z!"&'*+,:;<=>#_]{20}|[^a-zA-Z!"&'*+,:;<=>#_]{19}=|[^a-zA-Z!"&'*+,:;<=>#_]{19}=[^a-zA-Z!"&'*+,:;<=>#_]{17})$
More readable view with explanation :
`
^(
// 20 chars with = at 17
[^a-zA-Z!"&'*+,:;<=>#_]{16} // 16 allowed chars
= // followed by =
[^a-zA-Z!"&'*+,:;<=>#_]{3} // folowed by 3 allowed chars
|
[^a-zA-Z!"&'*+,:;<=>#_]{16} // 37 chars with = at 17
=
[^a-zA-Z!"&'*+,:;<=>#_]{20}
|
[^a-zA-Z!"&'*+,:;<=>#_]{19} // 20 chars with = at 20
=
|
[^a-zA-Z!"&'*+,:;<=>#_]{19} // 37 chars with = at 20
=
[^a-zA-Z!"&'*+,:;<=>#_]{17}
)$
`
I've omitted other symbols matching other symbols and just placed the [^=], you should have there code for all allowed symbols except =
var r = new Regex(#"^(([0-9\:\<\>]{16,16}=(([0-9\:\<\>]{20})|([0-9\:\<\>]{3})))|(^[^=]{19,19}=(([0-9\:\<\>]{17}))?))$");
/*
#"^(
([0-9\:\<\>]{16,16}
=
(([0-9\:\<\>]{20})|([0-9\:\<\>]{3})))
|
(^[^=]{19,19}
=
(([0-9\:\<\>]{17}))?)
)$"
*/
using {length,length} you can also specify the overall string length. The $ in the end and ^ in the beginning are important also.

How do I write regex to validate EIN numbers?

I want to validate that a string follows this format (using regex):
valid: 123456789 //9 digits
valid: 12-1234567 // 2 digits + dash + 7 digits
Here's an example, how I would use it:
var r = new Regex("^[1-9]\d?-\d{7}$");
Console.WriteLine(r.IsMatch("1-2-3"));
I have the regex for the format with dash, but can't figure how to include the non-dash format???
Regex regex = new Regex("^\\d{2}-?\\d{7}$");
This will accept the two formats you want: 2 digits then an optional dash and 7 numbers.
^ \d{9} | \d{2} - \d{7} $
Remove the spaces, they are there for readability.

Regular expression for Iranian mobile phone numbers?

How can I validate mobile numbers with a regular expression?
Iran Mobile phones have numeral system like this:
091- --- ----
093[1-9] --- ----
Some examples for prefixes:
0913894----
0937405----
0935673----
0912112----
Source: http://en.wikipedia.org/wiki/Telephone_numbers_in_Iran
Best Regular Expression for Detect Iranian Mobile Phone Numbers
I'm sure its best regular expression for detect iranian mobile number.
(0|\+98)?([ ]|-|[()]){0,2}9[1|2|3|4]([ ]|-|[()]){0,2}(?:[0-9]([ ]|-|[()]){0,2}){8}
use in javascript
var
mobileReg = /(0|\+98)?([ ]|-|[()]){0,2}9[1|2|3|4]([ ]|-|[()]){0,2}(?:[0-9]([ ]|-|[()]){0,2}){8}/ig,
junkReg = /[^\d]/ig,
persinNum = [/۰/gi,/۱/gi,/۲/gi,/۳/gi,/۴/gi,/۵/gi,/۶/gi,/۷/gi,/۸/gi,/۹/gi],
num2en = function (str){
for(var i=0;i<10;i++){
str=str.replace(persinNum[i],i);
}
return str;
},
getMobiles = function(str){
var mobiles = num2en(str+'').match(mobileReg) || [];
mobiles.forEach(function(value,index,arr){
arr[index]=value.replace(junkReg,'');
arr[index][0]==='0' || (arr[index]='0'+arr[index]);
});
return mobiles;
};
// test
console.log(getMobiles("jafang 0 91 2 (123) 45-67 jafang or +۹۸ (۹۱۵) ۸۰ ۸۰ ۸۸۸"));
support all option like these
912 123 4567
912 1234 567
912-123-4567
912 (123) 4567
9 1 2 1 2 3 4 5 6 7
9 -1 (2 12))3 45-6 7
and all with +98 or 0
+989121234567
09121234567
9121234567
or even persian numbers
+۹۸ (۹۱۵) ۸۰ ۸۰ ۸۸۸
and only detect true iranian operator numbers 091x 092x 093x 094x
for more info : https://gist.github.com/AliMD/6439187
Simplicity is the beautify of life . Try this one :
^09[0|1|2|3][0-9]{8}$
//091 for Hamrahe-Aval Operator
//092 for Rightel Operator
//093 | 090 for Irancel Oprator
Here is an Extension method in c# which I use regularly in my project :
public static bool IsValidMobileNumber(this string input)
{
const string pattern = #"^09[0|1|2|3][0-9]{8}$";
Regex reg = new Regex(pattern);
return reg.IsMatch(input);
}
Using like this :
If(!txtMobileNumber.Text.IsValidMobileNumber())
{
throw new Exception("Mobile number is not in valid format !");
}
According to the wiki page http://en.wikipedia.org/wiki/Telephone_numbers_in_Iran#Mobile_phones, the matches are:
091x-xxx-xxxx
0931-xxx-xxxx
0932-xxx-xxxx
0933-xxx-xxxx
0934-xxx-xxxx
0935-xxx-xxxx
0936-xxx-xxxx
0937-xxx-xxxx
0938-xxx-xxxx
0939-xxx-xxxx
which looks like
(the specific sequence 09) (1 followed by 0-9 OR 3 followed by 1-9) (7 digits)
Assuming you dont care about the dashes for now, this translates to
09 (1 [0-9] | 3 [1-9]) [0-9]{7} <-- spaces added for emphasis
09(1[0-9]|3[1-9])[0-9]{7} <-- actual regex
(the (..|..) does OR, the [0-9]{7} says match exactly 7 digits, ...)
If you want dashes in the specified location:
09(1[0-9]|3[1-9])-?[0-9]{3}-?[0-9]{4}
should match
How about this one ?
^(\+98?)?{?(0?9[0-9]{9,9}}?)$
working for:
09036565656
09151331685
09337829090
09136565655
09125151515
+989151671625
+9809152251148
check out the results here
^(\+98|0)?9\d{9}$
Will match with numbers like +989123456789 and
^[0][9][0-9][0-9]{8,8}$
match with numbers like 09123456789
^09\d{2}\s*?\d{3}\s*?\d{4}$
This will also allow spaces between numbers (if they are 4-3-4).
First of all lets write the reg ex for the numbers
^09\d{9}$ which means it must start with 09 and followed by 9 digits
or instead of \d you can use ^09[0-9]{9}$
after that
Regex objNotNaturalPattern=new Regex("[^09[0-9]{9}]");
objNotNaturalPattern.IsMatch(yourPhoneNumber);
Hope this helps.
in javascript you can use this code
let username = 09407422054
let checkMobile = username.match(/^0?9[0-9]{9}$/)
it will return
["9407422054", index: 0, input: "9407422054", groups: undefined]
the best regex pattern
(+?98|098|0|0098)?(9\d{9})
\A09\d{9} should do it for you
To support the 0903---- Irancell mobile numbers, use:
^(0|\+98)?([ ]|,|-|[()]){0,2}9[0|1|2|3|4]([ ]|,|-|[()]){0,3}(?:[0-9]([ ]|,|-|[()]){0,2}){8}$
I used this for Iran Mobile and worked for Irancell , rightell and MCI 0935-0939 ,0912,0901,0910,0902,0903,...
public static MobilePattern: string = '09[0-9]{9}$';
Regex:
/^(\{?(09)([1-3]){2}-([0-9]){7,7}\}?)$/
Matches:
- 0913-1234567
- 0933-1234567
Doesn't match:
- 0944-1234567
- 0955-1234567
If you don't want the '-', simply remove it from the regex
string sPattern = "^09[-.\\s]?\\d{2}[-.\\s]?\\d{3}[-.\\s]?\\d{4}$";
if (System.Text.RegularExpressions.Regex.IsMatch(stringToMatch, sPattern)){
System.Console.WriteLine("Phone Number is valid");
} else {
System.Console.WriteLine("Phone Number is invalid");
}
The expression above will match any number starting with 09 followed by a space, dot, or dash if present, then 2 digits, etc
ex: 09001234567 or 09 11 123 4567 or 09-01-123-4567 or 09.01.123.4567 or 0900.000.0000 or 0900-000-0000 or 0900.000-0000 etc
^09(1\d|3[1-9])-\d{3}-\d{4}$
is the regular expression that you need:
Starting with the beginning of the string (so no other digits sneak in)
09 is constant
1 can be combined with any subsequent digit, 3 cannot be combined with 0
-, and 3 digits
-, and 4 digits
End of string (again, so no other digits sneak in)
... but don't take my word for it, run it (I would recommend adding more test numbers):
List<string> possible = new List<string> { "091-555-8888",
"0915-888-4444",
"0930-885-8844",
"0955-888-8842" };
string regex = #"09(1\d|3[1-9])-\d{3}-\d{4}$";
foreach (string number in possible)
{
Console.WriteLine("{0} is{1} an Iranian number", number, Regex.IsMatch(number, regex) ? "" : " not");
}
It's Simple.
Iran TCI Phone in Any Format
Supports These Formats
+98217777777
98217777777
098217777777
0098217777777
217777777
0217777777
function IsIranPhone(phone) {
if (phone == null || phone ==undifined) {
return false;
}
return new RegExp("^((|0|98|098|0098|\\+98)[1-8][1-9][2-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9])$").test(phone);
}
Using this code in C#
public bool IsMobileValid(string mobile)
{
if (string.IsNullOrWhiteSpace(mobile))
return false;
if (Regex.IsMatch(mobile, #"(0|\+98)?([ ]|-|[()]){0,2}9[1|2|3|4]([ ]|-|[()])
{0,2}(?:[0-9]([ ]|-|[()]){0,2}){8}"))
return true;
return false;
}
//check phone number
function check_phone(number) {
var regex = new RegExp('^(\\+98|0)?9\\d{9}$');
var result = regex.test(number);
return result;
}
$('#PhoneInputId').focusout(function () {
var number = $('#crt-phone').val();
if (!check_phone(number)) {
your massage...
} else {
your massage...
}
});
this is best answer, i tested all answers but this is easy and best

Categories