-3

如何对字符串进行子串化,例如“A1(Value)”并返回“Value”

4

3 回答 3

1

您可以使用RegularExpression

Dim str = "A1(Value)...(anotherValue)"
Dim pattern = "\(([^)]*)\)"
Dim regex = New System.Text.RegularExpressions.Regex(pattern, System.Text.RegularExpressions.RegexOptions.Compiled)
Dim firstBracket = regex.Match(str)
If firstBracket.Value.Length <> 0 Then
    Dim inFirstBracket = firstBracket.Value.Substring(1, firstBracket.Value.Length - 2)
    'Value'
End If
于 2012-07-12T09:13:00.897 回答
0

用正则表达式检查

Dim result As String
Dim txt As String ="A1(Value)"
Dim re1 As String=".*?"
Dim re2 As String="((?:[a-z][a-z]+))"
Dim r As Regex = new Regex(re1+re2,RegexOptions.IgnoreCase Or RegexOptions.Singleline)
Dim m As Match = r.Match(txt)
If (m.Success) Then
    Dim word1=m.Groups(1)
    result = word1.ToString()
End If

得自:http ://txt2re.com/index-vb.php3?s=A1%28Value%29&2


或者只是将字符串从第 3 个字符拆分为 length-1

于 2012-07-12T09:08:57.773 回答
0

如果您不想使用正则表达式,则可以使用IndexOf来查找括号的位置并SubString返回括号内的字符串部分:

Dim txt As String = "A1(Value)"
Debug.WriteLine(txt.Substring(txt.IndexOf("(") + 1, txt.IndexOf(")") - txt.IndexOf("(") - 1))

请注意,如果字符串不包含左括号和右括号,这将引发异常,因此您可能需要添加一些错误检查

于 2012-07-12T13:12:18.063 回答