2012-11-19 56 views
0

如何檢查特定值以字符串或數字開始。在這裏我附上我的代碼。我得到錯誤喜歡預期的標識符。正則表達式vb.net

code 
---- 
Dim i As String 
dim ReturnValue as boolean 
    i = 400087 
    Dim s_str As String = i.Substring(0, 1) 

    Dim regex As Regex = New Regex([(a - z)(A-Z)]) 
    ReturnValue = Regex.IsMatch(s_str, Regex) 




error 

regx is type and cant be used as an expression 
+0

如果正則表達式不是必須的 - 在這裏使用正則表達式似乎有點過分 - 你可以簡單地使用'if Char.IsLetterOrDigit(TheString(0))' – igrimpe

回答

3

你的變量是regexRegex是變量的類型。

因此,它是:

ReturnValue = Regex.IsMatch(s_str, regex) 

但是你的正則表達式也有缺陷。 [(a - z)(A-Z)]創建的字符類與字符()-az,範圍A-Z完全匹配,並且沒有空格。

它看起來好像你想匹配字母。對於那只是使用\p{L}這是一個Unicode屬性,可以匹配任何語言字母的任何字符。

Dim regex As Regex = New Regex("[\p{L}\d]") 
+0

請注意字母*或開頭的數字* Q ...否則你幾乎可以得到它。 – Richard

+0

@Richard,感謝您的提示,我將其添加到我的解決方案中。 – stema

2

也許你的意思是

Dim _regex As Regex = New Regex("[(a-z)(A-Z)]") 
2
Dim regex As Regex = New Regex([(a - z)(A-Z)]) 
ReturnValue = Regex.IsMatch(s_str, Regex) 

注意大小寫不同,使用regex.IsMatch。您還需要引用正則表達式字符串:"[(a - z)(A-Z)]"


最後,那個正則表達式沒有意義,你在字符串中的任何地方匹配任何字母或開/關括號。

要匹配字符串的起始位置,您需要包含起始錨點^,類似於:^[a-zA-Z]匹配字符串開頭的任何ASCII字母。

2

檢查字符串開始於一個

ReturnValue = Regex.IsMatch(s_str,"^[a-zA-Z0-9]+") 

正則表達式說明:

^   # Matches start of string 
[a-zA-Z0-9] # Followed by any letter or number 
+   # at least one letter of number 

看到它在行動here