Regular Expression Chart Generator

I'm trying to make a regex pattern that will match this:

Name[0]/Something

      

or

Name/Something

      

The name of the verbs and something will always be known. I did for Name[0]/Something

but I want to create a pattern for this verb in one regex I tried sign [0]

as optional but it didn't work:

 var regexPattern = "Name" + @"\([\d*\]?)/" + "Something"

      

Do you know a generator where I will enter some verbs and it will make a template for me?

+3


source to share


5 answers


You were close, a regex will run Name(\[\d+\])?\/Something

.



+1


source


Use this:

Name(\[\d+\])?\/Something

      



  • \d+

    allows one or more digits
  • \[\d+\]

    allows you to enter one or more digits within [

    and ]

    . So he will allow [0]

    , [12]

    etc., but will reject[]

  • (\[\d+\])?

    allows the digit with brackets to be present either at zero or at one time
  • \/

    indicates a forward slash (only one)
  • Name

    and Something

    are string literals

Regex 101 Demo

+4


source


The problem is with the first '\' in your template before '('.
Here's 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);
}

      

+1


source


I think this is what you are looking for:

Name(\[\d+\])?\/Something

      

Litteral name

([\ d +])? number (1 or more digits) between brackets optional 1 or 0 times

/ Something Something literal

https://regex101.com/r/G8tIHC/1

0


source


var string = 'Name[0]/Something';

var regex = /^(Name)(\[\d*\])?\/Something$/;

console.log(regex.test(string));

string = 'Name/Something';

console.log(regex.test(string));
      

Run codeHide result


You are wrong with this pattern: \([\d*\]?)/

  • Don't need to use \

    before (

    (in this case)

  • ?

    after ]

    means: character ]

    zero or one time

So, if you want the template to [...]

render zero or one time, you can try:(\[\d*\])?

Hope this helps!

0


source







All Articles