3

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?

0

5 Answers 5

4

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 literals

Regex 101 Demo

Sign up to request clarification or add additional context in comments.

Comments

1

You were close, the regex Name(\[\d+\])?\/Something will do.

1 Comment

Your regex will match Name[0/Something as well
1

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);
}

Comments

0

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!

2 Comments

Will the result be correct if there is not digits inside brackets?
@AndriiLitvinov Maybe wrong, but the question doesn't mention about that.
0

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

3 Comments

How about more that one digit inside brackets?
@AndriiLitvinov that you add a + right after the d, signifying 1 or more of this character (number)
Yes, exactly, I think string represent index access which can be more that one digit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.