Resolved Using Regex

aaaron

Well-known member
Joined
Jan 23, 2011
Messages
216
Programming Experience
10+
Private Shared Function MakeValidFileName(ByVal name As String) As String
Dim invalidChars As String = System.Text.RegularExpressions.Regex.Escape(New String(System.IO.Path.GetInvalidFileNameChars))
Dim invalidRegStr As String = String.Format("([{0}]*\.+$)|([{0}]+)", invalidChars)
Return System.Text.RegularExpressions.Regex.Replace(name, invalidRegStr, "_")
End Function

Can you tell me what the line starting with invalidRegStr does?
 
String.Format Method (System) | Microsoft Docs
Replaces the format item in a specified string with the string representation of a corresponding object in a specified array.
In other words the placesholders {0} are replaced with the string in invalidChars variable.

Today you can use Interpolated Strings (Visual Basic) | Microsoft Docs instead of String.Format for same purpose.

4443
 
I should of said in my post, I know what the {0} do but:

I don't see why two of them and don't know what the other characters do.

Couldn't they all be added to invalidChars ?

Thanks
 
I don't see why two of them
The arguments can be added multiple places in the string.
and don't know what the other characters do
That is the regex expression, how sound that expression is you can decide yourself.
Lets say you take one illegal char \ and escape it \\ and put that in the placeholders, then you get this string/expression ([\\]*\.+$)|([\\]+)
Now you can copy and paste that into the expression box here Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript and you will get this explanation:
4446

You can also test input string the expression there.
If you want to learn regex you can for example go here: Regular-Expressions.info - Regex Tutorial, Examples and Reference - Regexp Patterns
 
In top-right menu you can 'edit thread' and set a resolved/answered thread prefix.
 
Back
Top