Regular expression for reference number - c#

I need to write the regular expression to fit a specific code pattern: the string to match has 18 integer characters and I need to check if in the first position there is 0 and in the second one 8 or 9. I wrote this expression, but it doesn't work:
Regex regex = new Regex(#"^(.{0}[0]{1}[8,9])(^\d{18}$)");
string compare = "082008014385161873";
if (regex.IsMatch(compare))
{
//true
}
Anyone can help me?

Try this regular expression. It does the following:
Verifies first digit as 0
Verifies second digit as a 8 or 9
Verifies that 16 more digits follow the first 2 digits
.
^0[89]\d{16}$

Use following regular expression:
^0[89]\d{16}$
Alternative using positive lookahead assertion:
^(?=0[89])\d{18}$

Related

Regex Not Finding All Matches C# [duplicate]

This question already has answers here:
Getting overlapping regex matches in C#
(2 answers)
Closed 4 years ago.
I researched, tested and used RegEx.101 and could not figure this out. I spent hours on it.
I am looking for 16 digit numbers.
Here is my regular expression: "[0-9]{16}"
Here is the code:
Regex ItemRegex = new Regex("[0-9]{16}");
// test with a 29 digit number
foreach (Match ItemMatch in ItemRegex.Matches("564654564553314342340968580654"))
{
i++;
}
I am expecting multiple matches but I am only getting the first 16 digits. How do I get the first 16 digits starting at position one, then the second 16 digits starting at position 2, then the third, etc?
Any thoughts, ideas, suggestions or solutions would be greatly appreciated and +1'd.
As ctwheels alluded to in his/her comment, to get overlapping matches like you want, you need to use a concept called a lookahead assertion, which is an expression that evaluates whether a condition is or is not satisfied without consuming those characters. These are called positive and negative lookahead assertions, respectively. Consider the following expression:
\d(?=(\d{15}))
The first \d will match a single digit and consume that character in the expression. This is followed by a positive lookahead assertion (denoted by (?=expression)) that tests whether that single digit is followed by another 15 digits, without consuming those 15 characters. Not consuming those characters means that the expression can find additional matches starting with the first character after the one matched by the initial \d. So:
var expression = #"\d(?=(\d{15}))";
var testString = "564654564553314342340968580654";
var regex = new Regex(expression);
foreach (Match match in regex.Matches(testString))
{
Console.WriteLine($"{match.Groups[0].Value}{match.Groups[1].Value}");
}
In my Console.WriteLine I am aggregating the contents of the two groups that will appear in each match: the first being the leading digit and the second being the group of 15 digits that follows it. The output of the above code is:
5646545645533143
6465456455331434
4654564553314342
6545645533143423
5456455331434234
4564553314342340
5645533143423409
6455331434234096
4553314342340968
5533143423409685
5331434234096858
3314342340968580
3143423409685806
1434234096858065
4342340968580654
See regex in use here
(?=(\d{16}))
(?=(\d{16})) Positive lookahead ensuring the following follows the current position
(\d{16}) Capture 16 digits into capture group 1
Result:
5646545645533143
6465456455331434
4654564553314342
6545645533143423
5456455331434234
4564553314342340
5645533143423409
6455331434234096
4553314342340968
5533143423409685
5331434234096858
3314342340968580
3143423409685806
1434234096858065
4342340968580654
So how does this work? Well, a lookahead (?=) is a zero-width assertion that checks whether or not the subpattern it contains matches at that specific location in the string. Since we haven't anchored our regex, this will attempt to match every position in the string.
So what does it mean to be a zero-width assertion? A lookaround actually matches characters and then gives up the match, returning only the result: match or no match. In our case, we've also added a capturing group to the positive lookahead assertion, thus allowing it to capture the result. What we end up with are empty matches (only matches at the particular locations where 16 digits follow) and the result (our 16 digits) in the capturing group.
Here is a approach without RegEx
// test with a 29 digit number
string input = "564654564553314342340968580654";
for (int i = 0; i < input.Length - 16+1; i++)
{
string result = string.Concat(input.Skip(i).Take(16));
if (result.All(x => char.IsDigit(x)))
{
Console.WriteLine(result);
}
}
https://dotnetfiddle.net/igGMSL

Regular expression for IR cell phone number

I am going to validate the IR cell phone number using the regular expression but it does not match it! For example '09126104851'.
What is the problem?
"^09[123456789]{2}(^0[123456789]{1}[0-9]{6}|[123456789]{1}[0-9]{7})$"
Your expression is equivalent to:
^09[1-9]{2}(^0[1-9]{1}[0-9]{6}|[1-9]{1}[0-9]{7})$
Which also can be written shorter as:
^09[1-9]{2}(^0[1-9]{1}\d{6}|[1-9]{1}\d{7})$
Now you've made an error in the middle is ^0. Probably you wanted [^0] ( everything not zero):
^09[1-9]{2}([^0][1-9]{1}\d{6}|[1-9]{1}\d{7})$
But the biggest problem is this part:
09[1-9]{2} matches in total 4 digits
[^0][1-9]{1}\d{6}matches in total 8 digits
[1-9]{1}\d{7} matches also 8 digits in total
So you are trying to match 8+4=12 digits while phone number has 11.
I bet you wanted expression to be:
^09[1-9]{2}([1-9]{1}\d{6}|[1-9]{1}\d{6})$
And now you will notice that alternating matches before and after | are
the same ! So this makes expression even smaller:
^09[1-9]{2}([1-9]{1}\d{6})$
If we can dismiss grouping of last 7 digits - we will notice similar parts:
[1-9]{2} and [1-9]{1}. This lets to reduce expression further:
^09[1-9]{3}\d{6}$
Demo
Because You have ^ symbol in the middle of regular expression.
^ means "in the start of the string".
You need regex from #msd : ^09\d{9}$
Use this regular expression instead: "^09\d{9}$"
For example:
System.Text.RegularExpressions.Regex.IsMatch("09126104851", #"^09\d{9}$")
Check it on fiddle: https://dotnetfiddle.net/8quyvL

Regular expression for decimal numbers with limiting character size

I'm trying to frame regular expression that matches the following criteria. Can you please suggest me a solution.
I tried with : ^[0-9]+(\.[0-9]{1,2})?$
It is working as expected but now i want to add a pattern to limit the character size up to 10(max) including period('.') in the text box.
Acceptance Criteria Values (When Char length is 6) :
.5, 0.5, 1.2, 33.33, 123.45
Rejection Criteria Values (When Char length is 6) :
.5.0, -0.5, 2.333, 122.456, 1234.56 (rejected because the length is 7 including dot ('.')
One way to do it is with a positive look-ahead. First check the condition then match:
string pattern = #"(?x) (?=^.{1,10}$ ) (^ \d+ (\.\d{1,2})? $) | (^\.\d{1,2}$)";
(?=^.{1,10}$ ) is the look-ahead, matches a string from 1 to 10 inclusive, then you match :
(^ \d+ (\.\d{1,2})? $) matches any digit followed by . and 1 or 2 other digits
| or
(^\.\d{1,2}$) matches . followed by 1 or 2 digits
Thanks,
I got answer like splitting into two regular expressions. One for numeric validation and another for length validation. If both conditions match then it is said as accepted.
Thanks for your valuable suggestions.
Naveen

regular expression for 4 number, a comma and 4 numbers

Using a regular expression, I would like to match the following string:
4232,2232
I have tried
^[0-9]+(,[0-9]+)$
However, it doesn't work as expected. I want to cater for 4 numbers, a comma and 4 numbers.
You can use the following:
\d{4},\d{4} //or ^\d{4},\d{4}$ with anchors for start and end of string
Explanation:
\d{4} match digits exactly 4 times (\d is shorthand notation for [0-9])
,\d{4} followed by comma and exactly 4 digits again
If i understand you correctly the RegEx you are looking for is basically:
(\d{4},\d{4})
This matches your provided expression as one group.
As an alternative you could write:
([0-9]{4},[0-9]{4})
which has the same result.
In C#, you can use Regex.IsMatch with the \b\d{4},\d{4}\b regex:
var found_value1 = Regex.IsMatch("4232,2232", #"\b\d{4},\d{4}\b");
var found_value2 = Regex.IsMatch("12345,2232", #"\b\d{4},\d{4}\b");
\b makes sure we match whole number.
Output:
true
false

How to give regular expression for Regex.ismatch function?

I am trying to write a regular expression for accepting a Number of length upto 14 and if they keep the decimal point then it should accept only 2 numbers after the decimal point.
I have tried it from this link below :
https://stackoverflow.com/a/9967694/861995
But, the same Regex.IsMatch function is not accepting the normal regex expression's starting with ^ and ending with $.
Please help me on this i am new to regular expressions
private void ChangedSellUp_KeyDown(object sender, KeyEventArgs e)
{
string pattern = "^[0-9]*$";
Regex rx = new Regex(pattern);
if (rx.IsMatch(ChangedSellUp.Text))
{
e.Handled = true;
}
}
Here ChangedSellup.Text is my text box value, i am trying to restrict the value based on 2 conditions
Its Should Accept only Numbers and length should not increase 14 till Decimal Point.
If decimal Point is there after that only 2 numbers are allowed.
e.g ; valid Values - 14.23, 12345678901234.23
Invalid values - 1.2344, 12345678901234.3455
Please help me with the regex ??
The best way to build regular expressions is with a Regex Tester. There's a really good one you can download called Cappucino, or you can use a web one, I favour http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx
Then it is simply a case of building the regex, I'm testing against 12345678901234.00
If you start with \d which is the regex pattern for a numeric digit then you get all sixteen matches you would expect.
Add a + which is short for one or more, so \d+ matches twice 12345678901234 and 00
If you limit to a range of only two digits i.e. \d{2} then you get 8 pairs of numbers
To add a . you need to escape the character as . is a pattern to match any digit, so instead use \.\d{2} to match only .00 (which was your optional part of the number)
If you pattern match a range of digits between 1 and 14 long \d{1,14} then you will match 12345678901234 (which is the main number) and 00
So now you can put it together, we make the post decimal point part optional by saying we want it either 0 or 1 times {0,1} or with a shorthand variant ? to give
\d{1,14}(\.\d{2})?
which matches correctly on these
12345678901234.00
123456.00
1
1234
and because I'm not matching the start and end of the line, also matches on these
500.00USD
$1000
Here's the Regex.IsMatch that does what you want:
Regex.IsMatch("12345678901234.12", #"^\d{1,14}(?:\.\d{1,2}){0,1}$")
That particular regex is for a number up to 14 digits before the decimal point and 1 or 2 digits after the decimal point (with the whole decimal part being optional)
A good place to test it is here: http://regexhero.net/tester/
Because you've mentioned ^ and $, I've included them in the regex, which will only parse lines with just the number (so, for example " 1234.12 " won't return true in the IsMatch, just remove the "^" and "$" if that is not important).
Another good resource for regex is this: http://www.mikesdotnetting.com/Article/46/CSharp-Regular-Expressions-Cheat-Sheet
UPDATE:
Since the goal is that the user cannot write anything other than something that satisfies that Regex in a textbox you can do this in the text changed event (key down is not a good option since you'd have to deal with converting KeyEventArg's Key to a char). So the easiest way to achieve what you need is:
private void TextBox1_TextChanged(object sender, TextChangedEventArgs e)
{
if (!Regex.IsMatch(TextBox1.Text, #"^\d{1,14}(?:\.\d{0,2}){0,1}$"))
{
TextBox1.Text = TextBox1.Text.Substring(0, TextBox1.Text.Length - e.Changes.Last().AddedLength);
TextBox1.CaretIndex = TextBox1.Text.Length;
}
}
Please notice the slight change in the regular expression that will accept a number followed by a dot, with no extra digits, this is because as you are writing a number with decimal places you'll be in a state where this happens, for example: "123."

Categories

Resources