为什么捕获组会导致双重匹配正则表达式 [英] Why capturing group results in double matches regex

查看:59
本文介绍了为什么捕获组会导致双重匹配正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下两个脚本:

第一个:" ".match(/(\s)/)

2nd:" ".match(/\s/)

结果

第一名:[" "," "]

2nd:[" "]

我不了解这种行为.据我所知,捕获组/同形异义的目的是要有一部分匹配项稍后在正则表达式中再次引用.但是很明显,这还不是全部.还是这种行为特定于 match split 方法.

I don't understand this behavior. As far as i knew purpose of capturing group/paranthesis was to have a section of match to be refered again later within regex. But clearly that's not all. Or is this behavior specific to match and split methods.

推荐答案

第一个脚本:第一个结果是整个模式,第二个结果是捕获组

First script: The first result is the whole pattern, the second is the capturing group

第二个脚本:唯一的结果就是整个模式.

Second script: the only result is the whole pattern.

捕获组不仅要在模式中稍后引用,它们还会显示在结果中.

Capturing groups are not only to refer later in the pattern, they are displayed in results too.

当您将捕获组与split一起使用时,捕获组将返回结果,并且由于应该使用分隔符对字符串进行切片,因此通常以
" "作为输入获得["", " ", ""]作为结果字符串和/(\s)/作为模式.

When you use a capturing group with split, the capturing group is returned with results and since the separator is supposed to slice the string, it is normal that you obtain ["", " ", ""] as result with
" " as input string and /(\s)/ as pattern.

有关拆分的更多信息.

当您写" ".match(/(\s)/)时,返回的结果是第一个匹配项.此结果是唯一的,并且包含:

When you write " ".match(/(\s)/) the result returned is the first match. This result is unique and contains:

  • 整个比赛
  • 捕获组
  • 比赛索引
  • 输入字符串

当您编写" ".match(/(\s)/g)时,返回的结果是所有匹配项:

When you write " ".match(/(\s)/g) the result returned is all the matches:

  • 全场比赛1
  • 全场比赛2

(在当前情况下,您只有一场比赛)

(in the present case you have only one match)

此行为是正常的. match方法具有两种不同的行为(带有或不带有/g).它是两种功能合而为一.为了在没有g修饰符的PHP(或其他语言)中进行比较,您具有两个不同的功能:preg_matchpreg_match_all

This behaviour is normal. The match method as two different behaviours (with or without /g). It is a kind of two functions in one. For comparison in PHP (or other languages) which doesn't have the g modifier, you have two different functions: preg_match and preg_match_all

这篇关于为什么捕获组会导致双重匹配正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆