Regex expression that match only these cases - c#

I have a regular expression in c# that should return IsMatch = true only when the input has the desired pattern but actually is returning true if some of the characters matches...How would be the correct regular expression?
Regex reg = new Regex(#"[0-9 \-+]"); //accept only numbers, spaces, minus character and plus character
string formularight="1123 - 4432+32124";//its correct
bool validformat=reg.IsMatch(formularight)) //returns true, ok
string formulawrong="1123a - 4432+32124"; //it has one letter ismatch should be false...
validformat=reg.IsMatch(formulawrong)) //returns true, not ok
I check later if each number is followed by a minus or plus sign before the next number but if it can be included in the regex validation...
I checked other regex questions and before someone suggest that i use a datatable to compute() the expresion or use some calculator logic please know that in this case the numbers are used like fields names that i will use to get some values from the database not numerical values per se. So i only need the regex validation before parsing the formula. Thanks
Valid examples for regex:
11123
112 - 1121
112-1121
1221111+554-111135678
44332-54-114
Invalid examples (letters present, not a + or - between numbers,...):
112 -
6543e
112 1121
6543e + 4432
-7632

Your Regular Expression finds several matches, because you didn't force it to match the whole input.
By using the following anchors, it will be forced to check the entire input.
^ - Start
$ - End
Regex:
^[0-9 \-+]*$
Regexr: http://regexr.com/3b97l

How about:
^\d+(?:\s*[+-]\s*\d+)*$
This works for your valid and invalid examples.
In order to match numbers in brackets:
^\[?\d+\]?(?:\s*[+-]\s*\[?\d+\]?)*$

You should start and end anchors in your regex:
Regex reg = new Regex(#"^[0-9 +-]+$");
to make sure whole input matches given set of characters.
isMatch Reference

Related

C# How to filtered datatable rows which containing alphanumeric with special characters using Regex

I have below data in my C# Datatable
What I want is to filter those data which has Alphanumeric with special characters like:
HOAUD039#
HOAUD00$
So I try below regex in my linq query:
var matches =
dt.AsEnumerable()
.Where(row => Regex.IsMatch(row["Empolyee_CRC"].ToString(),
"^[a-zA-Z0-9!##$&()\\-`.+,/\"]*$"))
.CopyToDataTable();
which returns me both Alphanumeric result and Alphanumeric with characters like below:
Now my question is simple and clear what is the right way to show results only having Alphanumeric with special characters.
I've also tried this regex but it is also not work
^(?:[\d,\/().]*[a-zA-Z][a-zA-Z\d,\/().]*)?$
You can try this based on your example patterns this will serve
^(?=.*\d)(?=.*[A-Za-z])(?=.*[!##$&()\\-`.+,\/\"]).*$
Explanation
^ - Anchor to start of string.
(?=.*\d) - Condition for checking at least one digit must be there in match.
(?=.*[A-Za-z]) - Condition for checking at least one character must be there in match.
(?=.*[!##$&()\\-.+,/\"])` - Condition for checking at least one special must be there in match.
.* - Match anything except newline.
$ - End of string.
Demo
In your regex you are using a single chararacter class which will only select one out of many, but your have 3 requirements.
In your second regex, everything is optional due to the * and the ?
You could use 3 positive lookaheads to assert your requirements:
^(?=.*\d)(?=.*[!##$&()`.+,\/\-])(?=.*[A-Z])[A-Z\d!##$&()`.+,\/\-]+$
In C#:
string pattern = #"^(?=.*\d)(?=.*[!##$&()`.+,\/\-])(?=.*[a-zA-Z])[a-zA-Z\d!##$&()`.+,\/-]+$";
That will match:
^ Start of string
(?=.*\d) Assert a digit
(?=.*[!##$&().+,/-])` Assert a special character
(?=.*[A-Za-z]) Assert a lowercase or uppercase character
[A-Za-z\d!##$&().+,/-]+` Match 1+ times only the allowed characters
$ End of the string
Regex demo | C# Demo

C# RegEx to match specific strings

I need to match (using regex) strings that can be like this:
required: custodian_{number 1 - 9}_{fieldType either txt or ssn}
optional: _{fieldLength 1-999}
So for example:
custodian_1_ssn_1 is valid
custodian_1_ssn_1_255 is valid
custodian or custodian_ or custodian_1 or custodian_1_ or custodian_1_ssn or custodian_1_ssn_ or custodian_1_ssn_1_ are not valid
Currently I am working with this:
(?:custodian|signer)_[1-9]?[0-9]_(?:txt|ssn)_[1-9][0-9]?(_[1-9]?[0-9]?[0-9]?)?
as my regex and my api is working to pick up:
custodian_1_txt_1
custodian_1_ssn_1
custodian_1_txt_1_255 <---- not matching the last "5"
any thoughts?
You may use pattern:
^custodian(?:_[a-z0-9]+)+$
^ Assert position beginning of line.
custodian Match literal substring custodian.
(?:_[a-z0-9]+)+ Non capturing group. Multiple sequence of _ followed by alphanumerics.
$ Assert position end of line.
You can check the correct matches here.
Obviously you can modify the pattern to add substring signer in non capturing group as:
^(?:custodian|signer)(?:_[a-z0-9]+)+$.
I suggest using \d for numbers not yours and this is my code try it:-
(?:custodian|signer)_[1-9]?[0-9]_(?:txt|ssn)_[1-9][0-9]?(_[1-9]?\d*)?
I just added a \d value to the end of your pattern to match all end digits before another match.
You could use an anchor to assert the start ^ and the end $ of the string and for the last part make at least the first 1-9 not optional or else it would match and underscore at the end:
^(?:custodian|signer)_[1-9]?[0-9]_(?:txt|ssn)_[1-9][0-9]?(_[1-9][0-9]?[0-9]?)?$
If you're only interested in the last digits, this super generic regex will do:
(?:.+)_(\d+)
If you do need to match the whole string, this worked:
^(?:custodian|signer)_\d+_(?:txt|ssn)(?:_\d+)?_(\d+)$

regular expression with hyphen in between numbers

I have to check whether the user entered string is in a particular format as below eg:
123-1234-1234567-1
ie after first 3 digit a hyphen, then after 4 digit another hyphen, after seven digit an hyphen then a single digit.
I used the below regular expression
#"^\(?([0-9]{3})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{7})[-. ]?([0-9]{1})$"
It is working fine for above expression but it will also pass the expression without - also
eg:- 123-1234-1234567-1 //pass
123123412345671 //also getting pass.
The second string should fail. What change i should do in the regular expression to achieve the same?
You can simply use:
^\d{3}-\d{4}-\d{7}-\d$
If you want to allow dot and space also as delimiter then use:
^\d{3}[-. ]\d{4}[-. ]\d{7}[-. ]\d$
The problems is that you are having optional quantifier ? after [. ].
Remove them, and it should work fine
#"^\(?([0-9]{3})\)?[-. ]([0-9]{4})[-. ]([0-9]{7})[-. ]([0-9]{1})$"
Regex demo
The ? makes the preceding pattern optional as it matches 0 or 1 character. So in the second example the regex engine safely matches zero - to get to match the entire string

Regular expression for specific combination of alphabets and numbers

I am trying to create regular expression for following type of strings:
combination of the prefix (XI/ YV/ XD/ YQ/ XZ), numerical digits only, and either no ‘Z’ or a ‘Z’ suffix.
For example, XD35Z should pass but XD01HW should not pass.
So far I tried following:
#"XD\d+Z?" - XD35Z passes but unfortunately it also works for XD01HW
#"XD\d+$Z" - XD01HW fails which is what I want but XD35Z also fails
I have also tried #"XD\d{1,}Z"? but it did not work
I need a single regex which will give me appropriate results for both types of strings.
Try this regex:
^(XI|YV|XD|YQ|XZ){1}\d+Z{0,1}$
I'm using quantifying braces to explicitly limit the allowed numbers of each character/group. And the ^ and $ anchors make sure that the regex matches only the whole line (string).
Broken into logical pieces this regex checks
^(XI|YV|XD|YQ|XZ){1} Starts with exactly one of the allowed prefixes
\d+ Is follow by one or more digits
Z{0,1}$ Ends with between 0 and 1 Z
You're misusing the $ which represents the end of the string in the Regex
It should be : #"^XD\d+Z?$" (notice that it appears at the end of the Regex, after the Z?)
The regex following the behaviour you want is:
^(XI|YV|XD|YQ|XZ)\d+Z?$
Explanation:
combination of the prefix (XI/ YV/ XD/ YQ/ XZ)
^(XI|YV|XD|YQ|XZ)
numerical digits only
\d+
‘Z’ or a ‘Z’ suffix
Z?$

Retrive a Digit from a String using Regex

What I am trying to do is fairly simple, although I am running into difficulty. I have a string that is a url, it will have the format http://www.somedomain.com?id=someid what I want to retrive is the someid part. I figure I can use a regular expression but I'm not very good with them, this is what I tried:
Match match = Regex.Match(theString, #"*.?id=(/d.)");
I get a regex exception saying there was an error parsing the regex. The way I am reading this is "any number of characters" then the literal "?id=" followed "by any number of digits". I put the digits in a group so I could pull them out. I'm not sure what is wrong with this. If anyone could tell me what I'm doing wrong I would appreciated it, thanks!
No need for Regex. Just use built-in utilities.
string query = new Uri("http://www.somedomain.com?id=someid").Query;
var dict = HttpUtility.ParseQueryString(query);
var value = dict["id"]
You've got a couple of errors in your regex. Try this:
Match match = Regex.Match(theString, #".*\?id=(\d+)");
Specifically, I:
changed *. to .* (dot matches all non-newline chars and * means zero or more of the preceding)
added a an escape sequence before the ? because the question mark is a special charcter in regular expressions. It means zero or one of the preceding.
changed /d. to \d* (you had the slash going the wrong way and you used dot, which was explained above, instead of * which was also explained above)
Try
var match = RegEx.Match(theString, #".*\?id=(\d+)");
The error is probably due to preceding *. The * character in regex matches zero or more occurrences of previous character; so it cannot be the first character.
Probably a typo, but shortcut for digit is \d, not /d
. matches any character, you need to match one or more digits - so use a +
? is a special character, so it needs to be escaped.
So it becomes:
Match match = Regex.Match(theString, #".*\?id=(\d+)");
That being said, regex is not the best tool for this; use a proper query string parser or things will eventually become difficult to manage.

Categories

Resources