【问题标题】:Regex to extract names from a string into a list正则表达式将名称从字符串中提取到列表中
【发布时间】:2016-03-04 02:09:17
【问题描述】:

如何使用正则表达式从以下字符串中提取名称:

Liam got 6,andy got 6

并将其添加到列表中,我尝试使用正则表达式,但找不到正确的表达式来仅提取名称,并且在该区域仍然有点不稳定。

任何帮助将不胜感激

【问题讨论】:

  • 名字总是在子句的前面(可预测的结构),还是有一组名字可以从中提取?
  • 名称将始终位于同一位置,但名称可能包含大小写字符
  • 剩下的句子会一直一样吗?我的意思是“得了 6”
  • 不,数字将在 0 到 10 之间
  • 也就是说,模式总是[name] got [number]?

标签: regex vb.net string


【解决方案1】:

对于简单的情况,我始终建议不要使用Regex,您可以使用string.Splitstring.ReplaceLINQ Where 这样做:

Dim names As String() = sentence.Replace("got ", "").Split(" ").Where(Function(t) Char.IsLetter(t(0))).ToArray()

假设你有这个sentence:

Dim separators As Char() = {",", " "}
Dim names As String() = sentence.Replace("got ", "").Split(separators, System.StringSplitOptions.RemoveEmptyEntries).Where(Function(t) Char.IsLetter(t(0))).ToArray()

一步一步发生的事情是:

"Andy got 6,may got 10, blue got 9, hERald got 0" 
"Andy 6,may 10, blue 9, hERald 0" 'After replace
"Andy" "6" "may" "10" "blue" "9" "hERald" "0" 'After split
"Andy" "may" "blue" "hERald" 'After where

【讨论】:

    【解决方案2】:

    这应该可以在 vb.net 中使用。

    (?<=^|,)\w+
    

    https://regex101.com/r/wT8rE9/1

    如果逗号后面可以有空格:

    (?<=^|,|,\s)\w+
    

    如果您对捕获组感到满意,您可以执行以下更有效的操作:

    (?:^|,\s*)(\w+)
    

    【讨论】:

    • 它可以工作,但是如果我想在正则表达式中包含逗号怎么办,所以它会像这样提取:liam,andy,dylan,ben
    • 如果您想使用替换的正则表达式路线,这可能会给您一个想法:regex101.com/r/eM6gL5/1
    猜你喜欢
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多