javascript正则表达式匹配重复项

标签 javascript html regex

<分区>

我有字符串,想通过正则表达式捕获一个片段:

var regex = new RegExp("(\s?.{0,2}the.{0,2}\s?)", "i");
var str= " the apple the apple the apple the apple the apple the apple the apple"
alert(str.match(regex))

目标是捕获第一个“max 3 symbol with(within) space”+“the”+“max 3 symbol with(within) space”

我不明白为什么结果是重复的 ------> a, the a

最佳答案

var regex = new RegExp("(\s?.{0,2}the.{0,2}\s?)", "i");
                        ^                     ^   unnecessary capturing group.

match 将为您处理表达式周围的捕获组。

你的正则表达式应该是:

var regex = new RegExp("\s?.{0,2}the.{0,2}\s?", "i");

关于javascript正则表达式匹配重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13160756/

相关文章:

javascript - 在 x 轴中使用时间时,浮点图未显示

javascript - 如何通过 javascript 设置复选框、单选按钮、下拉列表的样式?

c# - 如何匹配表达式中的参数名称?

c# - 将字符串与充满正则表达式的列进行匹配

r - 在R中,使用gsub删除除句点以外的所有标点符号

php - 如何反序列化字符串?

javascript - 使用 jQuery 从特定类获取 Input[type=(type)] 的值

javascript - react js : Image upload is not working in CKEditor

php - 使用 PHP 从 HTML 获取特定数据

html - Openwave 移动浏览器错误解释 CSS 子选择器和后代选择器