正则表达式只允许在VB.NET中使用点,字母和短划线

时间:2013-07-23 21:10:13

标签: .net regex vb.net

我有那个代码,它只用空格来诋毁单词并且以+开头......但我只允许点,字母和短划线......我认为它更简单:

Imports System.Text.RegularExpressions

Public Class Contactos

    ReadOnly pattern As String = "\s([^+\d\,]+),?"

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim cadena As String = " " & TextBox1.Text & ","

        Dim match As Match = Regex.Match(cadena, pattern)

        Do While match.Success
            frmMain.ListBox1.Items.Add(match.Groups(1).ToString)
            match = match.NextMatch()
        Loop
    End Sub
End Class

我该怎么办?

谢谢! :)

2 个答案:

答案 0 :(得分:1)

请尝试以下模式"(?<=(^|,\s))(?<word>[\.A-Za-z\-]+)($|,)"并使用命名组word来获取预期值:

    Do While match.Success
        frmMain.ListBox1.Items.Add(match.Groups("word").ToString)
        match = match.NextMatch()
    Loop

答案 1 :(得分:1)

尝试:

ReadOnly pattern As String = "\s([\.\-A-Za-z]+),?"

在第一个答案中,“\ w”模式将匹配字母,数字和下划线。我给你的“A-Za-z”部分只会匹配字母。