2014-11-04 47 views
0

我想添加一個catch語句來查看targetword是否有輸入的數字。如果一個字符串中有一個數字,就需要捕捉它vb

Console.WriteLine("Enter the word you want to guess: ") 
       targetWord = Console.ReadLine 
+0

你需要什麼? – 2014-11-04 15:07:03

+0

創建一個捕獲語句來阻止輸入的數字 – Cneaus 2014-11-04 15:08:18

+0

你有沒有試圖解決這個問題?你能顯示你的代碼嗎?你現在擁有的僅僅是要求輸入。 – xxbbcc 2014-11-04 15:08:43

回答

3

如果你想知道,如果給定的字符串中包含的數字,您可以使用Char.IsDigit

Dim input = Console.ReadLine() ' for example: abc123def 
Dim digits = input.Where(AddressOf Char.IsDigit) 
If digits.Any() Then 
    ' ... 
End If 

所以,如果你想要求用戶提供一個新的字符串,直到他進入一個沒有數字:

While digits.Any() 
    input = Console.ReadLine() 
    digits = input.Where(AddressOf Char.IsDigit) 
End While 
+0

非常感謝。 – Cneaus 2014-11-04 15:14:17

+0

或者更簡單地說,'input.Any(AddressOf Char.IsDigit)' – 2014-11-04 15:14:49

+0

@Cneaus:請注意,我已經編輯了答案,以顯示如何詢問用戶一個新值,直到他給出一個沒有數字的值。 – 2014-11-04 15:15:05

1

使用正則表達式:

If Regex.IsMatch("tes6t", "\d") Then 
    Console.WriteLine("Yes") 
End If 
0

試試這個:

''' <summary> 
''' Take a regular expression test pattern, a value to test the pattern against, and return true if it matches; false otherwise. 
''' </summary> 
''' <param name="testPattern">The regular expression against which the <paramref name="testValue"/> will be tested.</param> 
''' <param name="testValue">The value that will be tested against the regular expression <paramref name="testPattern"/>.</param> 
''' <returns>True if <paramref name="testValue" /> matches the regular expression <paramref name="testPattern" />.</returns> 
''' <remarks></remarks> 
Private Function ValueMatchesRegExpression(ByVal testPattern As String, ByVal testValue As String) As Boolean 
    Dim regEx As New System.Text.RegularExpressions.Regex(testPattern) 
    ValueMatchesRegExpression = regEx.IsMatch(testValue) 
End Function 

而且例如使用像這樣:

Debug.Print(ValueMatchesRegExpression("\d", targetWord)) 
+0

當'RegEx'類已經有一個共享的'IsMatch'方法來完成同樣的事情時,在自己的函數中包裝一些如此簡單的東西似乎很奇怪。換句話說,你的方法可以簡單地包含單行'Return RegEx.IsMatch(testValue,testPattern)',在這一點上它只是一個無增值包裝的共享方法。這並不是說永遠不會有一個理由來包裝一個共享方法,但在這種情況下推薦它沒有明顯的原因似乎很奇怪。 – 2014-11-04 15:24:53

+0

@StevenDoggart - 你可能是對的,但我總是試圖隱藏複雜性,甚至是非常小的複雜性。記住一個方法調用可能會更容易,特別是如果您將所有util方法放在一個地方,而不是嘗試記住'System.Text.RegularExpressions.Regex'的名稱空間,語法等。然後,也許不是。取決於我猜想的情況。我總是努力將不同的靜態庫調用集中到一個utils類中。 – 2014-11-04 15:30:20

相關問題