Regular expression for matching numbers inside brackets inside square brackets with additional text

Firstly, I am in C # here, so the RegEx fragrance I'm dealing with. And here is what I need to match:

[(1)] 

or

 [(34) Some Text - Some Other Text] 

So basically I need to know if the number between parentheses is numeric and ignore everything between the closing bracket and the closing square bracket. Any RegEx gurus can help?

+4
source share
7 answers

This should work:

 \[\(\d+\).*?\] 

And if you need to catch a number, just enclose \d+ in parentheses:

 \[\((\d+)\).*?\] 
+15
source

Do you need to match []? You can just ...

 \((\d+)\) 

(the numbers themselves will be in groups).

For instance...

 var mg = Regex.Match( "[(34) Some Text - Some Other Text]", @"\((\d+)\)"); if (mg.Success) { var num = mg.Groups[1].Value; // num == 34 } else { // No match } 
+1
source

Sort of:

 \[\(\d+\)[^\]]*\] 

Perhaps some acceleration is required?

0
source

How about "^ \ [\ ((d +) \)" (perl style not familiar with C #). You can safely ignore the rest of the line, I think.

0
source

Depending on what you are trying to do ...

 List<Boolean> rslt; String searchIn; Regex regxObj; MatchCollection mtchObj; Int32 mtchGrp; searchIn = @"[(34) Some Text - Some Other Text] [(1)]"; regxObj = new Regex(@"\[\(([^\)]+)\)[^\]]*\]"); mtchObj = regxObj.Matches(searchIn); if (mtchObj.Count > 0) rslt = new List<bool>(mtchObj.Count); else rslt = new List<bool>(); foreach (Match crntMtch in mtchObj) { if (Int32.TryParse(crntMtch.Value, out mtchGrp)) { rslt.Add(true); } } 
0
source

Like this? Assuming you only need to determine if the string matches, and not need to retrieve a numerical value ...

  string test = "[(34) Some Text - Some Other Text]"; Regex regex = new Regex( "\\[\\(\\d+\\).*\\]" ); Match match = regex.Match( test ); Console.WriteLine( "{0}\t{1}", test, match.Success ); 
0
source

Regex seems redundant in this situation. Here is the solution I used.

 var src = test.IndexOf('(') + 1; var dst = test.IndexOf(')') - 1; var result = test.SubString(src, dst-src); 
0
source

Source: https://habr.com/ru/post/1286380/


All Articles