I've copied a RegEx that's working in Javascript. But when I run it in C# it returns false. I'm not sure if it's my code iteslf that's incorrect or if it is the RegEx. This is my code.
bool isValid = true;
string nameInput = "Andreas Johansson";
string emailInput = "email#gmail.com";
string passwordInput = "abcABC123";
string namePattern = #"^[A-z]+(-[A-z]+)*$";
string emailPattern = #"^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$";
string passwordPattern = #"^(?=.*\d+)(?=.*[a-zA-Z])[0-9a-zA-Z!##$%]{6,50}$";
Regex nameRegEx = new Regex(namePattern);
Regex emailRegEx = new Regex(emailPattern);
Regex passwordRegEx = new Regex(passwordPattern);
if (model.CreateFullName.Length < 3 || !nameRegEx.IsMatch(nameInput))
isValid = false;
if (model.CreateEmail.Length < 3 || !emailRegEx.IsMatch(emailInput))
isValid = false;
if (model.CreatePassword.Length < 3 || !passwordRegEx.IsMatch(passwordInput))
isValid = false;
Thankful for inputs!
You should remove boundary slashes from pattern definitions. They are required for regex objects in javascript not .NET. e.g.:
string namePattern = #"^[A-z]+(-[A-z]+)*$";
string emailPattern = #"^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$";
string passwordPattern = #"^(?=.*\d+)(?=.*[a-zA-Z])[0-9a-zA-Z!##$%]{6,50}$";
UPDATE: you fixed them in your edit.
The name pattern still does not account for spaces in the input. Try following instead:
^[A-z]+([-\s][A-z]+)*$
Also note that [A-z] is not a correct pattern for matching alphabet letters. Use [A-Za-z] for matching ASCII alphabet letters, or \p{L} for matching any unicode letter.
The problem for [A-z] is that it matches these character too that reside after Z and before a:
[\]^_`
Related
I have 2 strings, one is main string and other is pattern string to be replaced. I want to replace the some part of main string with pattern string only if particular pattern is matched in main string.
Example:
string mainstring = "[def].[ijk] = [abc].[def].[ijk]";
string pattern = "[lmn].[def].[ijk]";
i want final string as
[lmn].[def].[ijk] = [abc].[def].[ijk]
i.e. if only 2 part is there in string than only replace not for 3 parts
i am using:
mainstring = mainstring.Replace("[def].[ijk]",pattern);
but it replaces as,
[lmn].[def].[ijk] = [abc].[lmn].[def].[ijk]
^-------+-------^
|
+-- don't replace here
but I want as
[lmn].[def].[ijk] = [abc].[def].[ijk]
EDIT: Additional rule for the replacement:
You can touch left hand side or right hand side but the pattern should be alone without anything at before or after.
I am trying to follow this rule:
i.e. if only 2 part is there in string than only replace not for 3 parts
(interpreting it as replace only if the matching pattern is not inbetween other parts, or: neither preceded nor follwed by a .)
This regular expression should satisfy this rule above:
string mainstring = "[def].[ijk] = [abc].[def].[ijk]";
// will replace only right side
//string mainstring = "[abc].[def].[ijk] = [def].[ijk]";
string replacement = "[lmn].[def].[ijk]";
string pattern = #"(?<!\.)\[def\].\[ijk\](?!\.)";
string output = Regex.Replace(mainstring, pattern, replacement);
EDIT:
if you need to transform you basic pattern into a regex format replace both parentheses:
string searchPattern = "[def].[ijk]";
searchPattern = searchPattern.Replace("[", #"\[").Replace("]", #"\]");
and place the result in between the look ahead and look behind pattern:
string pattern = #"(?<!\.)" + searchPattern + #"(?!\.)";
Explanation:
(?<!\.): the pattern is called negative lookahead. It will match only if the preceding character is not a . (dot)
(?!\.): the pattern is called negative lookbehind. It will match only if the following character is not a . (dot)
the replacement of [ ] to \[ \] is necessary because regex treats the parentheses as an interval or group and matches every character between the parentheses. Like [0-9] will match any digit between 0 and 9. But if you use an escape sequence #"\[0-9\]" it will take the parentheses as a character and match the pattern "[0-9]". I hope it became a little clearer
does this work for you?
string mainstring = "[def].[ijk] = [abc].[def].[ijk]";
string leftFillWith = "[lmn].[def].[ijk]";
string pattern = #"((\[lmn\]).)?((\[def\]).)?(\[ijk\])? =";
var expected= Regex.Replace(mainstring, pattern,match=> leftFillWith+" =" );
if only two parts are accepted:
string mainstring = "[def].[ijk] = [abc].[def].[ijk]";
string leftFillWith = "[lmn].[def].[ijk]";
// string pattern = #"((\[lmn\]).)?((\[def\]).)?(\[ijk\])? ="; //if any number of parts is accepted on left
string pattern = #"(\[def\]\.\[ijk\])(\s)+="; //if only two parts are accepted
string expected = Regex.IsMatch(mainstring,pattern)? Regex.Replace(mainstring, pattern, match => leftFillWith + " ="):mainstring;
Not good but work;
string mainstring = "[def].[ijk] = [abc].[def].[ijk]";
string pattern = "[lmn].[def].[ijk]";
string search ="[def].[ijk]";
string mainstring3 = "";
string[] mainstring2 = mainstring.Split(' ');
for (int i = 0; i < mainstring2.Length; i++)
{
if (mainstring2[i] == search)
{
mainstring2[i] = pattern;
}
if (i < mainstring2.Length - 1)
{
mainstring3 += mainstring2[i] + " ";
}
else
{
mainstring3 += mainstring2[i];
}
}
mainstring = mainstring3;
}
I want to find out, whether my string contains a text like #1, #a, #abc, #123, #abc123dsds and so on... ('#' character with one or more characters (digits and letters).
My code so far won't work:
string test = "#123";
boolean matches = test.Contains("#.+");
The matches variable is false.
String.Contains does not accept a regex.
Use Regex.IsMatch:
var matches = Regex.IsMatch(test, "#.+");
test.Contains("#.+"); does not "understand" regular expressions. It literally checks if the string test literally contains #.+ sequence of characters, which #123 does not contain.
Use Regex.IsMatch instead:
bool matches = Regex.IsMatch(test, "#.+");
Demo.
Or without regex, you can use a combination of StartsWith, Enumerable.Any and char.IsLetterOrDigit methods like;
var s = "#abc123dsds+";
var matches = s.Length > 1 && s.StartsWith("#") && s.Substring(1).All(char.IsLetterOrDigit);
You need to use Regex in order to use a regex pattern.
string text = "#123";
Regex rgx = new Regex("#[a-zA-Z0-9]+");
var match = rgx.Match(text);
bool matche = match.Success)
Well this worked for me. \# checks if it starts with #, \w checks if it is a word.
class Program
{
static void Main(string[] args)
{
string text = "#2";
string pat = #"\#(\w+)";
Regex r = new Regex(pat);
Match m = r.Match(text);
Console.WriteLine(m.Success);
Console.ReadKey();
}
}
I need to compare two strings, one of which uses '*' as a wildcard. I was thinking of using either an iterative or recursive method when I realized that RegEx would perform the task more quickly. Unfortunately, I am new to RegEx, and am not sure how to do this.
If I sent in the pattern "He**o", then "Hello" and "He7(o" should return true, but "Hhllo" should return false.
Assuming that you mean * to be a single-character wildcard, the correct substitution in a Regex pattern is a dot (.):
string pattern = "He**o";
string regexPattern = pattern.Replace("*",".");
Regex.IsMatch("Hello",regexPattern); // true
Regex.IsMatch("He7)o",regexPattern); // true
Regex.IsMatch("he7)o",regexPattern); // false
Regex.IsMatch("he7)o",regexPattern, RegexOptions.IgnoreCase); // true
You might also want to anchor the pattern with ^ (start of string) and $ (end of string):
regexPattern = String.Format("^{0}$", pattern.Replace("*","."));
If you expect it to be able to parse input strings with special characters, you'll can escape all other characters like this:
string regexPattern = String.Join(".",pattern.Split("*".ToCharArray())
.Select(s => Regex.Escape(s)).ToArray());
Compare the strings by using the char index in a for loop. If the pattern char (wildcard) appears, ignore the comparison and move on to the next comparison.
private bool Compare(string pattern, string compare)
{
if (pattern.Length != compare.Length)
//strings don't match
return false;
for(int x = 0, x < pattern.Length, x++)
{
if (pattern[x] != '*')
{
if (pattern[x] != compare[x])
return false;
}
}
return true;
}
Make Regex using "He..lo"
This is a case that will not be recognized
Regex r = new Regex("He..o");
string test = "Hhleo";
bool sucess = r.Match(a).Success;
This is a case that will be recognized
Regex r = new Regex("He..o");
string test = "He7)o";
bool sucess = r.Match(a).Success;
That's exactly what I've done in php today. When you add this:
if (pattern[x] != '*' && compare[x] != '*')
Then both strings can have wildcards. (hope that && means logical AND like in php)
I am looking for a regex to accept only numbers and comma but not 0,decimal,special characters,negative numbers and white-space between the numbers.It can allow White-space at the start and end of the value.Also It should allow 0 for 10,100,20 but I don't want the textbox to allow a single digit zero.
I have tried multiple options but I couldn't find one that solve my problem.
string testAnswer = textbox.value;
Regex answerRegex = new Regex(#"\s+(?<!-)[1-9][0-9,]*\s+");
if (testAnswer.Contains(","))
{
testAnswer = testAnswer.Replace(",", "");
Response.Write(testAnswer);
}
Match answerMatch = answerRegex.Match(testAnswer.Trim());
if (testAnswer == String.Empty || !answerMatch.Success)
{
valid = false;
answer.CssClass = "error";
}
else
{
answer.CssClass = "comp";
}
I think this will do what you want.
(\s+|^)(?<!-)[1-9][0-9,]*(\s+|$)
EDIT: I think I figured out your problem in your code. You're only checking based on Success property.
You need to check answerMatch.Groups in your code as well.
If you checked answerMatch.Groups[0] when you enter 7+9 string, you will realize that the match only matches 7 and discards the rest (+9) of the string.
Ok, I have tested this more extensively and I'm sure that this now works. I've modified your code a little bit so I can use it to demonstrate my test.
string testAnswer = "7 7+9700 700 007 400 -7 8";
bool valid = true;
string retVal = "";
Regex answerRegex = new Regex(#"(\s+|^)(?<!-)[1-9][0-9,]*(\s+|$)");
if (testAnswer.Contains(","))
{
testAnswer = testAnswer.Replace(",", "");
retVal = testAnswer;
}
MatchCollection answerMatch = answerRegex.Matches(testAnswer.Trim());
if (testAnswer == String.Empty || answerMatch.Count <= 0)
{
valid = false;
retVal = "error";
}
else
{
retVal = "comp";
foreach(Match m in answerMatch) {
Console.WriteLine(m.Groups[0].Value);
}
}
testAnswer holds my test string to be checked.
The output of the test program is as follows:
7
700
400
8
That output proves that it rejects negative numbers as well as special characters within the number string.
As for the regex string (\s+|^)(?<!-)[1-9][0-9,]*(\s+|$) here is the breakdown:
`(\s+|^) matches either the beginning of a string or leading whitespaces.
(?
[1-9][0-9,]* matches the numbers you are interested in including commas.
(\s+|$) matches either trailing whitespaces or end of the string.
If I got you right it should be
Regex answerRegex = new Regex(#"^[1-9][0-9]*$");
The * instead of the + lets pass 1, 10, etc.
I'm trying to make a Regular Expression in C# that will match strings like"", but my Regex stops at the first match, and I'd like to match the whole string.
I've been trying with a lot of ways to do this, currently, my code looks like this:
string sPattern = #"/&#\d{2};/";
Regex rExp = new Regex(sPattern);
MatchCollection mcMatches = rExp.Matches(txtInput.Text);
foreach (Match m in mcMatches) {
if (!m.Success) {
//Give Warning
}
}
And also tried lblDebug.Text = Regex.IsMatch(txtInput.Text, "(&#[0-9]{2};)+").ToString(); but it also only finds the first match.
Any tips?
Edit:
The end result I'm seeking is that strings like &# are labeled as incorrect, as it is now, since only the first match is made, my code marks this as a correct string.
Second Edit:
I changed my code to this
string sPattern = #"&#\d{2};";
Regex rExp = new Regex(sPattern);
MatchCollection mcMatches = rExp.Matches(txtInput.Text);
int iMatchCount = 0;
foreach (Match m in mcMatches) {
if (m.Success) {
iMatchCount++;
}
}
int iTotalStrings = txtInput.Text.Length / 5;
int iVerify = txtInput.Text.Length % 5;
if (iTotalStrings == iMatchCount && iVerify == 0) {
lblDebug.Text = "True";
} else {
lblDebug.Text = "False";
}
And this works the way I expected, but I still think this can be achieved in a better way.
Third Edit:
As #devundef suggest, the expression "^(&#\d{2};)+$" does the work I was hopping, so with this, my final code looks like this:
string sPattern = #"^(&#\d{2};)+$";
Regex rExp = new Regex(sPattern);
lblDebug.Text = rExp.IsMatch(txtInput.Text).ToString();
I always neglect the start and end of string characters (^ / $).
Remove the / at the start and end of the expression.
string sPattern = #"&#\d{2};";
EDIT
I tested the pattern and it works as expected. Not sure what you want.
Two options:
&#\d{2}; => will give N matches in the string. On the string it will match 2 groups, and
(&#\d{2};)+ => will macth the whole string as one single group. On the string it will match 1 group,
Edit 2:
What you want is not get the groups but know if the string is in the right format. This is the pattern:
Regex rExp = new Regex(#"^(&#\d{2};)+$");
var isValid = rExp.IsMatch("") // isValid = true
var isValid = rExp.IsMatch("xyz") // isValid = false
Here you go: (&#\d{2};)+ This should work for one occurence or more
(&#\d{2};)*
Recommend: http://www.weitz.de/regex-coach/