Regular expression to validate percentage - c#

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]

Related

Regex first digits occurrence

My task is extract the first digits in the following string:
GLB=VSCA|34|speed|1|
My pattern is the following:
(?x:VSCA(\|){1}(\d.))
Basically I need to extract "34", the first digits occurrence after the "VSCA". With my pattern I obtain a group but would be possibile to get only the number? this is my c# snippet:
string regex = #"(?x:VSCA(\|){1}(\d.))";
Regex rx = new Regex(regex);
string s = "GLB=VSCA|34|speed|1|";
if (rx.Match(s).Success)
{
var test = rx.Match(s).Groups[1].ToString();
}
You could match 34 (the first digits after VSCA) using a positive lookbehind (?<=VSCA\D*) to assert that what is on the left side is VSCA followed by zero or times not a digit \D* and then match one or more digits \d+:
(?<=VSCA\D*)\d+
If you need the pipe to be after VSCA the you could include that in the lookbehind:
(?<=VSCA\|)\d+
Demo
This regex pattern: (?<=VSCA\|)\d+?(?=\|) will match only the number. (If your number can be negative / have decimal places you may want to use (?<=VSCA\|).+?(?=\|) instead)
You don't need Regex for this, you can simply split on the '|' character:
string s = "GLB=VSCA|34|speed|1|";
string[] parts = s.Split('|');
if(parts.Length >= 2)
{
Console.WriteLine(parts[1]); //prints 34
}
The benefit here is that you can access all parts of the original string based on the index:
[0] - "GLB=VSCA"
[1] - "34"
[2] - "speed"
[3] - "1"
Fiddle here
While the other answers work really well, if you really must use a regular expression, or are interested in knowing how to get to that straight away you can use a named group for the number. Consider the following code:
string regex = #"(?x:VSCA(\|){1}(?<number>\d.?))";
Regex rx = new Regex(regex);
string s = "GLB:VSCA|34|speed|1|";
var match = rx.Match(s);
if(match.Success) Console.WriteLine(match.Groups["number"]);
How about (?<=VSCA\|)[0-9]+?
Try it out here

How to match string starting with one of the two specified chars followed by two or more digits

Matches : X23, A4858, A09387373, X90
Non-matches : G23, X23H, A48B59, A48BA484646
I came up with the following,
var rex = new Regex(#"^([AX](\d\d)+)");
but this matches X23H, A48B59,A48BA484646
How do I make sure it's a string starting with either 'A' or 'X' and then followed by two or more digits?
At least n of some pattern can be accomplished by using {n,}. You probably also want to mark the end of the string. Try doing:
var rex = new Regex(#"^([AX]\d{2,})$");
You're missing end of line anchor ($):
var rex = new Regex(#"^([AX](\d\d)+)$");
That's why your expression matches correctly in the beginning, but "grabs too much" at the end.
This should work fine...
It's taking 'A' or 'X' as First Character and followed by 2 digits.
var rex = new Regex(#"^[AX]{1}\d{2}$");
you can play with ^ and $ to best suit your requirement and also regexOptions.

Validate filename in c# through regex

I want to validate a filename with this format : LetterNumber_Enrollment_YYYYMMDD_HHMM.xml
string filename = "Try123_Enrollment_20130102_1200.xml";
Regex pattern = new Regex(#"[a-zA-z]_Enrollment_[0-9]{6}_[0-9]{4}\\.xml");
if (pattern.IsMatch(filename))
{
return isValid = true;
}
However, I can't make it to work.
Any thing that i missed here?
You are not matching digits at the beginning. Your pattern should be: ^[A-Za-z0-9]+_Enrollment_[0-9]{8}_[0-9]{4}\.xml$ to match given string.
Changes:
Your string starts with alphanumeric string before first _ symbol so you need to check both (letters and digits).
After Environment_ part you have digits with the length of 8 not 6.
No need of double \. You need to escape just dot (i.e. \.).
Demo app:
using System;
using System.Text.RegularExpressions;
class Test {
static void Main() {
string filename = "Try123_Enrollment_20130102_1200.xml";
Regex pattern = new Regex(#"^[A-Za-z0-9]+_Enrollment_[0-9]{8}_[0-9]{4}\.xml$");
if (pattern.IsMatch(filename))
{
Console.WriteLine("Matched");
}
}
}
Your Regex is nowhere near your actual string:
you only match a single letter at the start (and no digits) so Try123 doesn't match
you match 6 digits instead of 8 at the date part so 20130102 doesn't match
you have escaped your backslash near the end (\\.xml) but you've also used # on your string: with # you don't need to escape.
Try this instead:
#"[a-zA-Z]{3}\d{3}_Enrollment_[0-9]{8}_[0-9]{4}\.xml"
I've assumed you want only three letters and three numbers at the start; in fact you may want this:
#"[\w]*_Enrollment_[0-9]{8}_[0-9]{4}\.xml"
You can try the following, it matches letters and digits at the beginning and also ensures that the date is valid.
[A-Za-z0-9]+_Enrollment_(19|20)\d\d(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])_[0-9]{4}\.xml
As an aside, to test your regular expressions try the free regular expression designer from Rad Software, I find that it helps me work out complex expressions beforehand.
http://www.radsoftware.com.au/regexdesigner/

C# Regular Expression: {4} and more then 4 values possible

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}$");

RegEx Problem using .NET

I have a little problem on RegEx pattern in c#. Here's the rule below:
input: 1234567
expected output: 123/1234567
Rules:
Get the first three digit in the input. //123
Add /
Append the the original input. //123/1234567
The expected output should looks like this: 123/1234567
here's my regex pattern:
regex rx = new regex(#"((\w{1,3})(\w{1,7}))");
but the output is incorrect. 123/4567
I think this is what you're looking for:
string s = #"1234567";
s = Regex.Replace(s, #"(\w{3})(\w+)", #"$1/$1$2");
Instead of trying to match part of the string, then match the whole string, just match the whole thing in two capture groups and reuse the first one.
It's not clear why you need a RegEx for this. Why not just do:
string x = "1234567";
string result = x.Substring(0, 3) + "/" + x;
Another option is:
string s = Regex.Replace("1234567", #"^\w{3}", "$&/$&"););
That would capture 123 and replace it to 123/123, leaving the tail of 4567.
^\w{3} - Matches the first 3 characters.
$& - replace with the whole match.
You could also do #"^(\w{3})", "$1/$1" if you are more comfortable with it; it is better known.
Use positive look-ahead assertions, as they don't 'consume' characters in the current input stream, while still capturing input into groups:
Regex rx = new Regex(#"(?'group1'?=\w{1,3})(?'group2'?=\w{1,7})");
group1 should be 123, group2 should be 1234567.

Categories

Resources