Regular Expression (match word + some number) C# - c#

Sorry doing this the fast way of asking all the regex experts out there :)
What regex for C# can I use that matches the end of a word + some number
Eg. End of string matches with "Story" + 0 or more numbers
"ThisIsStory1" = true
"ThisIsStory2000" = true
"ThisIsStory" = true
"Story1IsThis" = false
"IsStoryThis1" = false
Hope this makes sense
A regular expression that I could plug into C# would be fantastic.
Thanks

You'll need something like this Story[0-9]*$
So it matches for story (ignoring anything before it, you may need to add more), then for 0 or more numbers between story and the end of the string.

Try [A-Za-z]*Story[0-9]*.
If you want to check against a whole line, ^[A-Za-z]*Story[0-9]*$.

to match number of characters before story and then story???? use this:
"[A-Za-z]*(s|S)tory\d*$"

string compare = "story1withANumber";
Regex regex = new Regex(#"[A-Za-z]+Story[0-9]*");
if (regex.IsMatch(compare))
{
//true
}
regex = new Regex("[0-9]");
if (regex.IsMatch(compare))
{
//true
}

A .NET regex that meets your criteria is:
Story\d*\b
(Use the Regex.IgnoreCase option if desired.)
\b matches the word boundary, so Story1IsThis will not match, but ThisIsAStory1 will. The word 'Story' does not need to end the string, so the string "ThisIsAStory234 ThisIsNot" will match on Story234.

Related

c# regex clarification [duplicate]

What is the regular expression (in JavaScript if it matters) to only match if the text is an exact match? That is, there should be no extra characters at other end of the string.
For example, if I'm trying to match for abc, then 1abc1, 1abc, and abc1 would not match.
Use the start and end delimiters: ^abc$
It depends. You could
string.match(/^abc$/)
But that would not match the following string: 'the first 3 letters of the alphabet are abc. not abc123'
I think you would want to use \b (word boundaries):
var str = 'the first 3 letters of the alphabet are abc. not abc123';
var pat = /\b(abc)\b/g;
console.log(str.match(pat));
Live example: http://jsfiddle.net/uu5VJ/
If the former solution works for you, I would advise against using it.
That means you may have something like the following:
var strs = ['abc', 'abc1', 'abc2']
for (var i = 0; i < strs.length; i++) {
if (strs[i] == 'abc') {
//do something
}
else {
//do something else
}
}
While you could use
if (str[i].match(/^abc$/g)) {
//do something
}
It would be considerably more resource-intensive. For me, a general rule of thumb is for a simple string comparison use a conditional expression, for a more dynamic pattern use a regular expression.
More on JavaScript regexes: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
"^" For the begining of the line "$" for the end of it. Eg.:
var re = /^abc$/;
Would match "abc" but not "1abc" or "abc1". You can learn more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

evaluate filename with regex

I have a bit of code to evaluate a filename using a regex, this works fine, but I want to add in a 2nd pattern of out_\d\d\d\d\d\d_ (then up to 150 character to hold an address).
Obviously I don't want to have \d 150 times, can anyone tell me the best way to to this?
thanks
REGEX_PATTERN = #"out_\d\d\d\d\d\d";
if (!Regex.Match(Path.GetFileNameWithoutExtension(e.Name), REGEX_PATTERN).Success) {
return;
}
You want:
REGEX_PATTERN = #"^out_\d{6}(?:_.{1,150})?$";
This breaks down as
`^` - start of string
`out_\d{6}` - `out_` followed by 6 digits
`(?:_.{1,50})?` - an optional string of _ followed by 1-150 characters
`$` - end of string
Try this out:
REGEX_PATTERN = #"out_\d{1,150}";
OR
// For strict boundary match
REGEX_PATTERN = #"^out_\d{1,150}$";

Regular Expression to get all characters before "-"

How can I get the string before the character "-" using regular expressions?
For example, I have "text-1" and I want to return "text".
So I see many possibilities to achieve this.
string text = "Foobar-test";
Regex Match everything till the first "-"
Match result = Regex.Match(text, #"^.*?(?=-)");
^ match from the start of the string
.*? match any character (.), zero or more times (*) but as less as possible (?)
(?=-) till the next character is a "-" (this is a positive look ahead)
Regex Match anything that is not a "-" from the start of the string
Match result2 = Regex.Match(text, #"^[^-]*");
[^-]* matches any character that is not a "-" zero or more times
Regex Match anything that is not a "-" from the start of the string till a "-"
Match result21 = Regex.Match(text, #"^([^-]*)-");
Will only match if there is a dash in the string, but the result is then found in capture group 1.
Split on "-"
string[] result3 = text.Split('-');
Result is an Array the part before the first "-" is the first item in the Array
Substring till the first "-"
string result4 = text.Substring(0, text.IndexOf("-"));
Get the substring from text from the start till the first occurrence of "-" (text.IndexOf("-"))
You get then all the results (all the same) with this
Console.WriteLine(result);
Console.WriteLine(result2);
Console.WriteLine(result21.Groups[1]);
Console.WriteLine(result3[0]);
Console.WriteLine(result4);
I would prefer the first method.
You need to think also about the behavior, when there is no dash in the string. The fourth method will throw an exception in that case, because text.IndexOf("-") will be -1. Method 1 and 2.1 will return nothing and method 2 and 3 will return the complete string.
Here is my suggestion - it's quite simple as that:
[^-]*
This is something like the regular expression you need:
([^-]*)-
Quick tests in JavaScript:
/([^-]*)-/.exec('text-1')[1] // 'text'
/([^-]*)-/.exec('foo-bar-1')[1] // 'foo'
/([^-]*)-/.exec('-1')[1] // ''
/([^-]*)-/.exec('quux')[1] // explodes
I dont think you need regex to achieve this. I would look at the SubString method along with the indexOf method. If you need more help, add a comment showing what you have attempted and I will offer more help.
You could just use another non-regex based method. Someone gave the suggestion of using Substring, but you could also use Split:
string testString = "my-string";
string[] splitString = testString.Split("-");
string resultingString = splitString[0]; //my
See http://msdn.microsoft.com/en-US/library/ms228388%28v=VS.80%29.aspx for another good example.
If you want use RegEx in .NET,
Regex rx = new Regex(#"^([\w]+)(\-)*");
var match = rx.Match("thisis-thefirst");
var text = match.Groups[1].Value;
Assert.AreEqual("thisis", text);
Find all word and space characters up to and including a -
^[\w ]+-

Regular Expression For Alphanumeric String With At Least One Alphabet Or Atleast One Numeric In The String

To test one alphanumeric string we usually use the regular expression "^[a-zA-Z0-9_]*$" (or most preferably "^\w+$" for C#). But this regex accepts numeric only strings or alphabet only strings, like "12345678" or "asdfgth".
I need one regex which will accept only the alphanumeric strings that have at-least one alphabet and one number. That is to say by the regex "ar56ji" will be one of the correct strings, not the previously said strings.
Thanks in advance.
This should do it:
if (Regex.IsMatch(subjectString, #"
# Match string having one letter and one digit (min).
\A # Anchor to start of string.
(?=[^0-9]*[0-9]) # at least one number and
(?=[^A-Za-z]*[A-Za-z]) # at least one letter.
\w+ # Match string of alphanums.
\Z # Anchor to end of string.
",
RegexOptions.IgnorePatternWhitespace)) {
// Successful match
} else {
// Match attempt failed
}
EDIT 2012-08-28 Improved efficiency of lookaheads by changing the lazy dot stars to specific greedy char classes.
Try this out:
"^\w*(?=\w*\d)(?=\w*[a-zA-z])\w*$"
There is a good article about it here:
http://nilangshah.wordpress.com/2007/06/26/password-validation-via-regular-expression/
This should work:
"^[a-zA-Z0-9_]*([a-zA-Z][0-9]|[0-9][a-zA-Z])[a-zA-Z0-9_]*$"
This will match:
<zero-or-more-stuff>
EITHER <letter-followed-by-digit> OR <digit-followed-by-letter>
<zero-or-more-stuff>
By ensuring you have either a digit followed by letter or a letter followed by digit, you are enforcing the requirement to have at least one digit and at least one letter. Note that I've left out the _ above, because it wasn't clear whether you would accept that as a letter, a digit, or neither.
Try this one ^([a-zA-z]+[0-9][a-zA-Z0-9]*)|([0-9]+[a-zA-z][a-zA-Z0-9]*)$
Simple is better. If you had a hard time writing it originally, you're (or some other poor sap) is going to have a hard time maintaining it or modifying it. (And I think that I see some possible holes in the approaches listed above.)
using System.Text.RegularExpressions;
boolean IsGoodPassword(string pwd){
int minPwdLen = 8;
int maxPwdLen = 12;
boolean allowableChars = false;
boolean oneLetterOneNumber = false;
boolean goodLength = false;
string allowedCharsPattern = "^[a-z0-9]*$";
//Does it pass the test for containing only allowed chars?
allowableChars = Regex.IsMatch(pwd, allowedCharsPattern , RegexOptions.IgnoreCase));
//Does it contain at least one # and one letter?
oneLetterOneNumber = Regex.IsMatch(pwd, "[0-9]")) && Regex.IsMatch(pwd, "[a-z]", RegularExpressions.IgnoreCase));
//Does it pass length requirements?
goodLength = pwd.Length >= minPwdLength && pwd.Length <= maxPwdLength;
return allowableChars && oneLetterOneNumber && goodLength;
}

How do I use a regular expression to match strings that don't start with an empty space?

I want a regular expression that checks that a string doesn't start with an empty space.
I want to do something like this:
Is the following ValidationExpression right for it?
string ValidationExpression = #"/^[^ ]/";
if (!String.IsNullOrEmpty(GroupName) && !Regex.IsMatch(GroupName, ValidationExpression))
{
}
How about "^\S"
This will make sure that the first character is not a whitespace character.
You can also use:
if(GroupName.StartsWith(string.Empty)); // where GroupName == any string
Regex rx = new Regex(#"^\s+");
You can check with
Match m1 = rx.Match(" "); //m1.Success should be true
Match m2 = rx.Match("qwerty "); //m2.Success should be false
Something like this, maybe :
/^[^ ]/
And, for a couple of notes about that :
The first ^ means "string starts with"
The [^ ] means "one character that is not a space"
And the // are regex delimiter -- not sure if they are required in C#, though.

Categories

Resources