Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby中正则表达式的子字符串提取问题_Ruby_Regex - Fatal编程技术网

Ruby中正则表达式的子字符串提取问题

Ruby中正则表达式的子字符串提取问题,ruby,regex,Ruby,Regex,我试图通过使用正则表达式在Ruby中进行一些子字符串提取,并且遇到了一些问题,其中regexp是“过度选择性的” 以下是我尝试匹配的目标字符串: “带有3个数字、2个逗号和6388个未包含的其他值的示例string。” 我试图提取的是所提供语句中的数值。为了解释逗号,我提出了表达式/(\d{1,3}(,\d{1,3})*)/ 在IRB中测试以下内容,这是代码和结果: string = "Exam­ple strin­g with 3 numbe­rs, 2 comma­s, and 6,388­

我试图通过使用正则表达式在Ruby中进行一些子字符串提取,并且遇到了一些问题,其中regexp是“过度选择性的”

以下是我尝试匹配的目标字符串:

“带有3个数字、2个逗号和6388个未包含的其他值的示例string。”

我试图提取的是所提供语句中的数值。为了解释逗号,我提出了表达式
/(\d{1,3}(,\d{1,3})*)/

在IRB中测试以下内容,这是代码和结果:

string = "Exam­ple strin­g with 3 numbe­rs, 2 comma­s, and 6,388­ other­ value­s that are not inclu­ded."
puts strin­g.scan(/(\­d{1,3}(,\d­{1,3})*)/)­
=> "[[\"3\", nil], [\"2\", nil], [\"6,388\", \",388\"]]"
我要找的是类似于
[“3”、“2”、“6388”]
的东西。以下是我需要帮助纠正的问题:

  • 为什么Ruby为每个非逗号分隔的匹配组包含
    nil
    ,我如何调整正则表达式/匹配策略来删除它并获得一个“平面”数组
  • 如何防止正则表达式与试图匹配的子字符串(即
    “6388”
    )的子表达式匹配
  • 我确实尝试使用
    .match()
    ,但遇到了一个问题,即它只返回
    “3”
    (可能是匹配的第一个值),而没有其他明显的信息。试图用
    [1]
    [2]
    对其进行索引会导致
    nil

如果模式中有捕获组,则返回数组数组以表示所有组

对于每个匹配,将生成一个结果并将其添加到结果中 数组或传递到块。如果模式不包含组,则每个组 单个结果包含匹配的字符串,
$&
如果该模式 包含组,每个单独的结果本身就是一个包含 每组一个条目

通过删除捕获组或将
(…)
替换为非捕获组
(?:…)
,您将得到不同的结果:

string = "Example string with 3 numbers, 2 commas, and 6,388 other values ..."
string.scan(/\d{1,3}(?:,\d{1,3})*/)   # no capturing group
# => ["3", "2", "6,388"]