简体   繁体   中英

String.split() and replaceAll from Java to VB.net

I have several lines of code in Java that i need to convert VB.net:

1) s.replaceAll("f\\((.*)\\).*", "$1").trim()
2) s.split("\\,")
3) s.split("\\s+")
4) s.replaceAll("[Tt]hreshold\\s*=(.*)", "$1").trim()

I used Java to VB.net converter and here is the result:

1) s = s.ReplaceAll("f\((.*)\).*", "$1").Trim()
2) s.Split("\,", True)
3) s.Split("\s+", True)
4) s.ReplaceAll("[Tt]hreshold\s*=(.*)", "$1").Trim()

The problem i have is that this code does not work. Lines 2 and 3 have an error "Argument matching parameter 'separator' narrows from 'String' to '1 - Dimensional array of Char'". Lines 1 and 4 say that 'ReplaceAll' is not a member of 'String'. I am a bit puzzled, how could I do make it work the exact same way as Java code? Help is very much appreciated.

In Java, unlike .NET, methods on String allow regular expressions. In .NET, the Regular Expressions library (located in System.Text.RegularExpressions ) would be used instead. The converter is failing to identify this difference.

In both Java and .NET, strings are immutable, that is, the Java code does not change the value of s , and the lines by itself are no-ops. You would need to capture the result of each call, for instance as a variable, for later use.

In the first line:

s.replaceAll("f\\((.*)\\).*", "$1").trim()

This can be expressed using the Regex library as

Regex.Replace(s, "f\((.*)\).*", "$1").Trim()

Now take the second line:

s.split("\\,")

This expression simply splits a comma-delimited string into an array. (The comma does not need to be escaped; this expression is the same as s.split(",") ). The equivalent VB code does not require regular expressions and is simply:

s.split(","c)

(or, assigned to a variable, dim Sa as String() = s.Split(","c) .)


The third line:

s.split("\\s+")

This pattern uses a regular expression to use a string delimited on whitespace (any number of characters). The Regex.Split method returns the same result:

Regex.Split(s, "\s+")

Finally, take:

s.replaceAll("[Tt]hreshold\\s*=(.*)", "$1").trim()

This construct is functionally identical to the first, albeit with a different pattern. It can be expressed in VB as:

Regex.Replace(s, "[Tt]hreshold\\s*=(.*)", "$1").Trim()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM