Convert PHP Regex to .NET

Which is equivalent below in .NET Regex

preg_replace("/\(([^()]*+|(?R))*\)/","", $string); 

I am always struggling with regex, I tried to get it right with myregextester.com, and I just can't get the syntax right, so it turns this on.

 1.0 (Mac OS X Mail 9.0 \(3083\)) 

IN

 1.0 

I want to delete comments (even if they are nested)

I used this, but it did not work for nested comments.

  Dim regex As New Regex(String.Format("\{0}.*?\{1}", "(", "(")) Return regex.Replace(s, String.Empty) 
+4
source share
1 answer

The regular expression in question is a consistent PCRE regular expression matching the balanced parentheses. To match balanced parentheses in .NET, you can use this regex :

 \((?>(?:[^()])+|\((?<DEPTH>)|\)(?<-DEPTH>))*(?(DEPTH)(?!))\) 

VB.NET implementation:

 Dim R As Regex = New Regex(" \( " & _ " (?> " & _ " [^()]+ " & _ " | " & _ " \( (?<DEPTH>) " & _ " | " & _ " \) (?<-DEPTH>) " & _ " )* " & _ " (?(DEPTH)(?!)) " & _ " \) ", _ RegexOptions.IgnorePatternWhitespace) Dim str As String = R.Replace("1.0 (Mac OS X Mail 9.0 \(3083\))", "") 

Watch the IDEONE demo

To remove spaces, simply add [ ]* or \s* to the beginning of the pattern.

If you just want to remove all characters between the leftmost and rightmost parentheses, use greedy matching:

 (?s)[ ]*\(.*\) 

Or

 (?s)\p{Zs}*\(.*\) 

See demo

The \p{Zs} Unicode category class matches any Unicode spaces, and [ ] matches the regular literal space. Note that \s matches all possible spaces, including newlines.

+2
source

All Articles