Elahe
Elahe

Reputation: 1399

check is valid my string in custom format? the number of brackets

I need a regex for check this format:

[some digits][some digits][some digits][some digits][some digits][some digits]#

"some digits" means each number (0 or 1 or 2 or 3 or .... ), 2 digits, 3 digits, or more...

but it's important that each open bracket be closed before another open one...

actually I want to check the format and also get the number of []. I tried this code for getting number of [] :

Regex.Matches( input, "[]" ).Count

but it didnt work.

thanks for helping

Upvotes: 1

Views: 81

Answers (1)

zx81
zx81

Reputation: 41838

This is the regex you're looking for:

^(\[\d+\])+#$

See the demo.

Sample Code for the Count

var myRegex = new Regex(@"^(\[\d+\])+#$");
string bracketCount = myRegex.Match(yourString).Groups[1].Count;

Explanation

  • The ^ anchor asserts that we are at the beginning of the string
  • ( starts capture Group 1
  • \[opens a bracket
  • \d+ matches one or more digits
  • \] matches the closing bracket
  • ) closes Group 1
  • + matches this 1 or more times
  • # the hash
  • The $ anchor asserts that we are at the end of the string

Upvotes: 3

Related Questions