c# making a regex to accept numnerical values - c#

I am trying to make a regex on field which accepts in the following:
Where X is a numerical value between 0-9 so 3 numbers before the - and three after the dash.
I started with the following but I got lost in adding validation after the dash.
([0-9-])\w+([0-9-])

3 digits, a dash then 3 digits:
\d{3}-\d{3}

var example = "123-455";
var pattern = #"\A(\d){3}-(\d){3}\Z";
var result = Regex.Match(example, pattern);
This will not only search for the pattern within your string, but also make sure that the beginning and end of the pattern is at the beginning and end of your target string. This ensures that you won't get a match e.g. for:
"silly123-456stuff" or "0123-4567".
In other words, it both looks for a pattern, and limits its length by anchoring it to the begining and end of the string.

string pattern = #"^([0-9]{3})-([0-9]{3})$";
Regex rgx = new Regex(pattern);

I would add the the beginning and end of line to the regex
^\d{3}-\d{3}$
^ = at the beginning of the line
\d = a number
{3} = three times
- = a dash
\d = a number
{3} = three times
$ = the end of the line
Not setting the start and end of line could catch invalid patterns, such as Text123-4858
Edit: even better than line markers, the anchors proposed by Kjartan are the correct answer in this case.

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 :)

Build a regex that does not contain the first and last character you are looking for in the match

I have the following problem.
This is what the regex looks like:
var regexTest = new Regex(#"'\d.*\d#");
This is what the string looks like:
var text = "dsadsadsadsa('1.222222#dsadsa'";
That is the result of what I would like to have:
1.222222
That's the result I'm getting right now ...:
'1.222222#
You want to extract the float number in between ' and ", use
var text = "dsadsadsadsa('1.222222#dsadsa'";
var regexTest = new Regex(#"'(\d+\.\d+)#");
var m = regexTest.Match(text);
if (m.Success)
{
Console.WriteLine(m.Groups[1].Value);
}
Here, (\d+\.\d+) captures any 1+ digits, . and then 1+ digits into Group 1 that you may access using match.Groups[1].Value. However, only access that value if there was a match, or you will get an exception (see m.Success part in my demo snippet).
See the regex demo:
Just enclose the part you want to get in parentheses, so that you can get it as a group:
var regexTest = new Regex(#"'(\d.*\d)#");
-----------------------------^------^----
In '\d.*\d# you are are matching ' followed by a digit, any character 0+ times followed by a digit. That would match '1.222222# but also for example '1.A2# because of the .*
To don't match the ' and the # you could use a positive lookahead and a positive lookbehind to assert that they are there. If you only want to match digits then the .* could be left out.
(?<=')\d+\.\d+(?=#)
Regex demo

Regex to find special pattern

I have a string to parse. First I have to check if string contains special pattern:
I wanted to know if there is substrings which starts with "$(",
and end with ")",
and between those start and end special strings,there should not be
any white-empty space,
it should not include "$" character inside it.
I have a little regex for it in C#
string input = "$(abc)";
string pattern = #"\$\(([^$][^\s]*)\)";
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(input);
foreach (var match in matches)
{
Console.WriteLine("value = " + match);
}
It works for many cases but failed at input= $(a$() , which inside the expression is empty. I wanted NOT to match when input is $().[ there is nothing between start and end identifiers].
What is wrong with my regex?
Note: [^$] matches a single character but not of $
Use the below regex if you want to match $()
\$\(([^\s$]*)\)
Use the below regex if you don't want to match $(),
\$\(([^\s$]+)\)
* repeats the preceding token zero or more times.
+ Repeats the preceding token one or more times.
Your regex \(([^$][^\s]*)\) is wrong. It won't allow $ as a first character inside () but it allows it as second or third ,, etc. See the demo here. You need to combine the negated classes in your regex inorder to match any character not of a space or $.
Your current regex does not match $() because the [^$] matches at least 1 character. The only way I can think of where you would have this match would be when you have an input containing more than one parens, like:
$()(something)
In those cases, you will also need to exclude at least the closing paren:
string pattern = #"\$\(([^$\s)]+)\)";
The above matches for example:
abc in $(abc) and
abc and def in $(def)$()$(abc)(something).
Simply replace the * with a + and merge the options.
string pattern = #"\$\(([^$\s]+)\)";
+ means 1 or more
* means 0 or more

C# regexp negative lookahead

i have a problem with replacing characters after specific character. For example i want to replace first 'aa' to '33' with this code.
string str = "dc1aaaafg";
string pattern = #"a{2}(?!(1))";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(str, "33");
but the result is 'dc13333fg'. It replaced the second group after '1'. I need to replace only first group like 'dc133aafg'. How can i achive this. I have a large string and it can be many replacing, this is just example.
Regex.Replace() is global. It will replace as many times as the pattern matches*.
You could use Regex.Replace(String, String, Int32) to limit the number of operations.
string result = rgx.Replace(str, "33", 1);
Or you change the pattern to a look-behind.
Regex rgx = new Regex(#"(?<=1)a{2}");
string result = rgx.Replace(str, "33");
* Note that Replace() is global, but not incremental. Using the expression a{2} on "aaaaaa" to with the replacement "ba" will result in "bababa", not in "bbbbba".
There is an overload to the Replace method in which you can specify the number of times. Specify 1 and it shall do only the first match.
string result = rgx.Replace(str, "33", 1);
A regex pattern cannot express that only the first match is relevant.
Use Regex.Match to get the position and length of the first match. Then use Substring (or Remove followed by Insert) to construct a new string from the old string, that has the replacement you want.
Try with a negative look behind : (a{2})(?<!\1{2})
(a{2}) # 'a' two times
(?<! # negative look behind
\1{2} # '\1' is the captured group 'a' twice to "jump" over the captured group
)

Trouble creating a Regex expression

I'm trying to create a regex expression what will accept a certain format of command. The pattern is as follows:
Can start with a $ and have two following value 0-9,A-F,a-f (ie: $00 - $FF)
or
Can be any value except for "&<>'/"
*if the value start with $ the next two values after need to be a valid hex value from 00-ff
So far I have this
Regex correctValue = new Regex("($[0-9a-fA-F][0-9a-fA-F])");
Any help will be greatly appreciated!
You just need to add "\" symbol before your "$" and it works:
string input = "$00";
Match m = Regex.Match(input, #"^\$[0-9a-fA-F][0-9a-fA-F]$");
if (m.Success)
{
foreach (Group g in m.Groups)
Console.WriteLine(g.Value);
}
else
Console.WriteLine("Didn't match");
If I'm following you correctly, the net result you're looking for is any value that is not in the list "&<>'/", since any combination of $ and two alphanumeric characters would also not be in that list. Thus you could make your expression:
Regex correctValue = new Regex("[^&<>'/]");
Update: But just in case you do need to know how to properly match the $00 - $FF, this would do the trick:
Regex correctValue = new Regex("\$[0-9A-Fa-f]{2}");
In Regular Expression $ use for Anchor assertion, and means:
The match must occur at the end of the string or before \n at the end of the line or string.
try using [$] (Character Class for single character) or \$ (Character Escape) instead.

Categories