Reputation: 380
I'm trying to do regex pattern which will match to this:
Name[0]/Something
or
Name/Something
Verbs Name and Something will be always known.
I did for Name[0]/Something
, but I want make pattern for this verb in one regex
I've tried to sign [0]
as optional but it didn't work :
var regexPattern = "Name" + @"\([\d*\]?)/" + "Something"
Do you know some generator where I will input some verbs and it will make pattern for me?
Upvotes: 3
Views: 3220
Reputation: 7706
The problem is with first '\' in your pattern before '('.
Here is what you need:
var str = "Name[0]/Something or Name/Something";
Regex rg = new Regex(@"Name(\[\d+\])?/Something");
var matches = rg.Matches(str);
foreach(Match a in matches)
{
Console.WriteLine(a.Value);
}
Upvotes: 1
Reputation: 4981
Use this:
Name(\[\d+\])?\/Something
\d+
allows one or more digits\[\d+\]
allows one or more digits inside [
and ]
. So it will allow [0]
, [12]
etc but reject []
(\[\d+\])?
allows digit with brackets to be present either zero times or once\/
indicates a slash (only one)Name
and Something
are string literalsUpvotes: 4
Reputation: 9381
i think this is what you are looking for:
Name(\[\d+\])?\/Something
Name litteral
([\d+])? a number (1 or more digits) between brackets optional 1 or 0 times
/Something Something litteral
https://regex101.com/r/G8tIHC/1
Upvotes: 0
Reputation: 13182
You were close, the regex Name(\[\d+\])?\/Something
will do.
Upvotes: 1
Reputation:
var string = 'Name[0]/Something';
var regex = /^(Name)(\[\d*\])?\/Something$/;
console.log(regex.test(string));
string = 'Name/Something';
console.log(regex.test(string));
You've tried wrong with this pattern: \([\d*\]?)/
No need to use \
before (
(in this case)
?
after ]
mean: character ]
zero or one time
So, if you want the pattern [...]
displays zero or one time, you can try: (\[\d*\])?
Hope this helps!
Upvotes: 0