I'm in need of a regular expression that checks if the input is exactly 4 numbers.
I'm using "\d{4}" (also tried "\d\d\d\d").
But if you enter 5 numbers, it also says the input is valid.
[TestMethod]
public void RegexTest()
{
Regex expr = new Regex("\\d{4}");
String a = "4444", b = "4l44", c = "55555", d = "5 55";
Match mc = expr.Match(a);
Assert.IsTrue(mc.Success);
mc = expr.Match(b);
Assert.IsFalse(mc.Success);
***mc = expr.Match(c);
Assert.IsFalse(mc.Success)***;
mc = expr.Match(d);
Assert.IsFalse(mc.Success);
}
(it's the c that is 'true' but should be false, the others work)
Thanks in advance,
~Sir Troll
If it must be exactly 4, then you need to use $ and ^ to mark end and start of the input:
Regex expr = new Regex(#"^\d{4}$");
Note I'm also using verbatim string literals here, so save on sanity - then you don't need to C#-escape all your regex-escape-characters. Only " needs escaping in the C# (to "").
"55555" contains "5555", which is valid... So the string contains a match, even though the match isn't the complete string. See Marc's answer for the solution
a string with 5 digits also contains 4 digits, so you have to make sure that you also add start and end of string contraints.
This should work as your Regex:
Regex expr = new Regex(#"^\d{4}$");
Related
I want to validate input string such that
5.0 is correct
5.5% is correct
So I started with the following code:
string decimalstring1 = "10000.55";
string decimalstring2 = "5%5%";
string expression = #"^\d|\d%";
Regex objNotNumberPattern = new Regex(expression);
Console.WriteLine(objNotNumberPattern.IsMatch(decimalstring1));
Console.WriteLine(objNotNumberPattern.IsMatch(decimalstring2));
Console.ReadLine();
But the problem is that with input like 5%5% it gives correct
How can I modify this expression to make this work?
string[] inputs = new string[] {
"1000.55",
"1000.65%",
"100",
"100%",
"1400%",
"5.5",
"5.5%",
"x",
".%"
};
string expression = #"^\d+[.]?\d*%?$";
Regex objNotNumberPattern = new Regex(expression);
foreach (var item in inputs)
Console.WriteLine(objNotNumberPattern.IsMatch(item));
UPDATE
string expression = #"^(\d+|\d+[.]\d+)%?$";
You get partial matches, because your expression does not anchor both sides. Your regex anchors the beginning, but not the end of the match.
Moreover, the placement of the left anchor ^ is incorrect, because it applies only to the left sub-expression
Adding a $ at the end should help:
^(\d|\d%)$
However, this is suboptimal: since the prefix of both expressions is the same, and they differ by an optional suffix %, you could use %? to simplify the expression:
^\d+%?$
This is better, but it would not match decimal point. To add this capability, change the expression as follows:
^(\d+|\d*[.]\d+)%?$
You're expression is the following: match when you find either of the following: a single digit at the start of the input string, or a single digit anywhere, followed by %. Probably not what you intended. I'd try something like this:
var expression = #"^\d+(\.\d+)?%?$";
This would translate to: match a positive number of digits at the start of the string, optionally followed by a dot and any number of digits (fractional part), optionally ending with a % sign.
You could try this ^\d+([.]\d+)?%?$ it works with: (tested)
1000.55
1000.65%
100
100%
1400%
5.5
5.5%
Hope it helps!
i think this is the best one :
^\d{0,2}(\.\d{1,4})? *%?$
source : Here
this worked for me:
/(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{0,2})?)$/
For only two decimals and no more than 100 [0.00 - 100.00]
I am really struggling with Regular Expressions and can't seem to extract the number from this string
"id":143331539043251,
I've tried with this ... but I'm getting compilation errors
var regex = new Regex(#""id:"\d+,");
Note that the full string contains other numbers I don't want. I want numbers between id: and the ending ,
Try this code:
var match = Regex.Match(input, #"\""id\"":(?<num>\d+)");
var yourNumber = match.Groups["num"].Value;
Then use extracted number yourNumber as a string or parse it to number type.
If all you need is the digits, just match on that:
[0-9]+
Note that I am not using \d as that would match on any digit (such as Arabic numerals) in the .NET regex engine.
Update, following comments on the question and on this answer - the following regex will match the pattern and place the matched numbers in a capturing group:
#"""id"":([0-9]+),"
Used as:
Regex.Match(#"""id"":143331539043251,", #"""id"":([0-9]+),").Groups[1].Value
Which returns 143331539043251.
If you are open to using LINQ try the following (c#):
string stringVariable = "123cccccbb---556876---==";
var f = (from a in stringVariable.ToCharArray() where Char.IsDigit(a) == true select a);
var number = String.Join("", f);
I've written a Regular expression which should validate a string using the following rules:
The first four characters must be alphanumeric.
The alpha characters are followed by 6 or 7 numeric values for a total length of 10 or 11.
So the string should look like this if its valid:
CCCCNNNNNN or CCCCNNNNNNN
C being any character and N being a number.
My expression is written: #"^[0-9A-Za-z]{3}[0-9A-Za-z-]\d{0,21}$";
My regex match code looks like this:
var cc1 = "FOOBAR"; // should fail.
var cc2 = "AAAA1111111111"; // should succeed
var regex = #"^[0-9A-Za-z]{3}[0-9A-Za-z-]\d{0,21}$";
Match match = Regex.Match( cc1, regex, RegexOptions.IgnoreCase );
if ( cc1 != string.Empty && match.Success )
{
//"The Number must start with 4 letters and contain no numbers.",
Error = SeverityType.Error
}
I'm hoping someone can take a look at my expression and offer some feedback on improvements to produce a valid match.
Also, am I use .Match() correctly? If Match.Success is true, then does that mean that the string is valid?
The regex for 4 alphanumeric characters follows by 6 to 7 decimal digits is:
var regex = #"^\w{4}\d{6,7}$";
See: Regular Expression Language - Quick Reference
The Regex.Match Method returns a Match object. The Success Property indicates whether the match is successful or not.
var match = Regex.Match(input, regex, RegexOptions.IgnoreCase);
if (!match.Success)
{
// does not match
}
The following code demonstrates the regex usage:
var cc1 = "FOOBAR"; // should fail.
var cc2 = "AAAA1111111"; // should succeed
var r = new Regex(#"^[0-9a-zA-Z]{4}\d{6,7}$");
if (!r.IsMatch(cc2))
{
Console.WriteLine("cc2 doesn't match");
}
if (!r.IsMatch(cc1))
{
Console.WriteLine("cc1 doesn't match");
}
The output will be cc1 doesn't match.
The following code is using a regular expression and checks 4 different patterns to test it, see output below:
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var p1 = "aaaa999999";
CheckMatch(p1);
p1 = "aaaa9999999";
CheckMatch(p1);
p1 = "aaaa99999999";
CheckMatch(p1);
p1 = "aaa999999";
CheckMatch(p1);
}
public static void CheckMatch(string p1)
{
var reg = new Regex(#"^\w{4}\d{6,7}$");
if (!reg.IsMatch(p1))
{
Console.WriteLine($"{p1} doesn't match");
}
else
{
Console.WriteLine($"{p1} matches");
}
}
}
Output:
aaaa999999 matches
aaaa9999999 matches
aaaa99999999 doesn't match
aaa999999 doesn't match
Try it as DotNetFiddle
Your conditions give:
The first four characters must be alphanumeric: [A-Za-z\d]{4}
Followed by 6 or 7 numeric values: \d{6,7}
Put it together and anchor it:
^[A-Za-z\d]{4}\d{6,7}\z
Altho that depends a bit how you define "alphanumeric". Also if you are using ignore case flag then you can remove the A-Z range from the expression.
Try the following pattern:
#"^[A-za-z\d]{4}\d{6,7}$"
I have the below situation
I have to match something like
abc#(x,-12d)
or
abc#(x,-12d, 24d) etc.
That means the last parameter is optional.
I have already made the regular expression and it works but since I donot know how to make optional , henceforth I am using two different regExpression.
public static bool ValidFn(string input)
{
string regEx1 = #"^[a-zA-Z]*#\([A-Za-z0-9]+,[-|+]?\d+[dwmqy],[-|+]?\d+[dwmqy]\)";
string regEx2 = #"^[a-zA-Z]*#\([A-Za-z0-9]+,[-|+]?\d+[dwmqy]\)";
Regex r1 = new Regex(regEx1);
Regex r2 = new Regex(regEx2);
Match m1 = r1.Match(input);
Match m2 = r2.Match(input);
if (m1.Success || m2.Success) return true;
else return false;
}
How can I make regExp1 as optional so that I can eliminate the use of regExp2.
Thanks
The ? character in regex means "Repeat 0 or 1 time". Therefore, it makes a statement optional.
You want to capture the last ", 24d" when it exists. You need to wrap what captures ", 24d" with a ? character.
This regex will do :
string regEx1 = #"^[a-zA-Z]*#\([A-Za-z0-9]+,[-|+]?\d+[dwmqy](,\s*[-|+]?\d+[dwmqy])?\)";
Note that i've added a \s* to capture white spaces after the ,
Optional parts are marked with ?, aren't they? You have already used it in [-|+]?.
I need for text like "joe ($3,004.50)" to be filtered down to 3004.50 but am terrible at regex and can't find a suitable solution. So only numbers and periods should stay - everything else filtered. I use C# and VS.net 2008 framework 3.5
This should do it:
string s = "joe ($3,004.50)";
s = Regex.Replace(s, "[^0-9.]", "");
The regex is:
[^0-9.]
You can cache the regex:
Regex not_num_period = new Regex("[^0-9.]")
then use:
string result = not_num_period.Replace("joe ($3,004.50)", "");
However, you should keep in mind that some cultures have different conventions for writing monetary amounts, such as: 3.004,50.
You are dealing with a string - string is an IEumerable<char>, so you can use LINQ:
var input = "joe ($3,004.50)";
var result = String.Join("", input.Where(c => Char.IsDigit(c) || c == '.'));
Console.WriteLine(result); // 3004.50
For the accepted answer, MatthewGunn raises a valid point in that all digits, commas, and periods in the entire string will be condensed together. This will avoid that:
string s = "joe.smith ($3,004.50)";
Regex r = new Regex(#"(?:^|[^w.,])(\d[\d,.]+)(?=\W|$)/)");
Match m = r.match(s);
string v = null;
if (m.Success) {
v = m.Groups[1].Value;
v = Regex.Replace(v, ",", "");
}
The approach of removing offending characters is potentially problematic. What if there's another . in the string somewhere? It won't be removed, though it should!
Removing non-digits or periods, the string joe.smith ($3,004.50) would transform into the unparseable .3004.50.
Imho, it is better to match a specific pattern, and extract it using a group. Something simple would be to find all contiguous commas, digits, and periods with regexp:
[\d,\.]+
Sample test run:
Pattern understood as:
[\d,\.]+
Enter string to check if matches pattern
> a2.3 fjdfadfj34 34j3424 2,300 adsfa
Group 0 match: "2.3"
Group 0 match: "34"
Group 0 match: "34"
Group 0 match: "3424"
Group 0 match: "2,300"
Then for each match, remove all commas and send that to the parser. To handle case of something like 12.323.344, you could do another check to see that a matching substring has at most one ..