如何为数字和字母制作正则表达式?每当我输入它只读取字符串,而不是随机化。假设我输入312< - 它将是无效的标识符,因为它的数字变量不是有序的。在字母上我尝试了a123456789,所以当我输入a1,a2,a3时,它会作为标识符读取,因为它按顺序排列。我还想创建另一个将数字和字母组合在一起的变量。
Dim input As String = txtInput.Text
Dim symbol As String = "\s*([-+*/=])\s*"
Dim numbers As String = "123456789" //("[0-9]") <-- doesnt work?
Dim letters As String = "abcdefghijklmnopqrstuvwxyz" // ("[a-z]")<-also
Dim substrings() As String = Regex.Split(input, symbol)
For Each match As String In substrings
If symbol.Contains(match) Then
lstOutput.Items.Add(match & " - operator")
ElseIf numbers.Contains(match) Then
lstOutput.Items.Add(match & " - number")
ElseIf letters.Contains(match) Then
lstOutput.Items.Add(match & " - identifier")
Else
lstOutput.Items.Add(match & " - Invalid Identifier")
End If
Next
输入:c1 + 2c + cad + c1b
预期产出:
c1 - 标识符
2c - 无效标识符//无效,因为第一个字符是数字
cad - 标识符
c1b - 标识符
答案 0 :(得分:1)
您可以使用Regex.IsMatch
对数字和标识符使用正则表达式模式。
数字模式:
^
- 字符串开头[0-9]*
- 0+位数\.?
- 一个可选的点[0-9]+
- 1+位数$
- 字符串结尾标识符模式:
^
- 字符串开头[a-zA-Z_]
- ASCII字母或_
[a-zA-Z0-9_]*
- 0+ ASCII字母,数字或_
$
- 字符串结尾。
Dim input As String =&#34; c1 + 2c + cad + c1b&#34; Dim符号As String =&#34; \ s *([ - + / =])\ s &#34; Dim numbers As String =&#34; ^ [0-9] 。?[0-9] + $&#34; Dim letters As String =&#34; ^ [a-zA-Z _] [a-zA-Z0-9 _] $&#34;
Dim substrings()As String = Regex.Split(输入,符号)
对于每个匹配字符串在子字符串中 如果是Regex.IsMatch(匹配,符号)那么 Console.WriteLine(匹配&amp;&#34; - 运算符&#34;) ElseIf Regex.IsMatch(匹配,数字)然后 Console.WriteLine(匹配&amp;&#34; - 数字&#34;) ElseIf Regex.IsMatch(匹配,字母)然后 Console.WriteLine(匹配&amp;&#34; - 标识符&#34;) 其他 Console.WriteLine(匹配&amp;&#34; - 无效的标识符&#34;) 万一 下一步
请参阅VB.NET demo输出
c1 - identifier
+ - operator
2c - Invalid Identifier
+ - operator
cad - identifier
+ - operator
c1b - identifier