Regex匹配:被空格或行首包围,但不匹配
Regex Matching: Surrounded by space or start of line, but not matched
这就是我目前所拥有的:/(^|['s])#'d+/g
我的测试字符串是:"#123 it should match this: #1234, but not this: http://example.org/derp#6326 . How about on a new line?'n'n#1284"
当我尝试匹配时,我会得到以下匹配:
"#123"
" #1234"
"'n#1284"
(假设这是一个真正的断线)
我试图通过将?:
添加到分组中并用括号包围我想要的内容来更改正则表达式:/(?:^|['s])(#'d+)/g
,但这不起作用,并且提供了相同的匹配
如何只匹配#
+数字,而之前没有任何内容?
内存捕获可以完成任务:
var re = /(?:^|['s])(#'d+)/g;
while (match = re.exec(str)) {
console.log(match[1]);
}
演示
事实上,你确实捕捉到了你想要的,你只需要看看捕捉组内部的内容,而不是整个比赛。。。
尝试
var myString = "#123 it should match this: #1234, but not this: http://example.org/derp#6326 . How about on a new line?'n'n#1284";
var myRegex = /(?:^|'s)(#'d+)/g;
var allMatches = [];
while((result = myRegex.exec(myString)) != null) {
var match = result[1]; // get the first capturing group of the current match
allMatches.push(match);
}
您可以在这里清楚地看到regex捕获的内容
subject= "#1234, but not this: http://example.org/derp#6326";
match = subject.match(/^'s*?#('d+)/m);
if (match != null) {
var result = match[1]
}
Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «'s*?»
Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the character “#” literally «#»
Match the regular expression below and capture its match into backreference number 1 «('d+)»
Match a single digit 0..9 «'d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
相关文章:
- 高库存时期时间与时区不匹配
- react路由器使用简单的javascript路由器配置来处理不匹配的路径
- Javascript:图像与单选按钮的值不匹配
- 文本区域(jQuery)的结果不匹配
- 如果状态不匹配,则缩小为丑陋
- 为什么我网页的facebook点赞数与该网页的facebook页面不匹配
- 使用jscodeshift添加表达式时,错误{..}与类型字符串不匹配
- JavaScript正则表达式不匹配
- row.entity.xxxx属性doensn'排序后不匹配
- Url.Content中的Url不匹配
- 控件坐标与组坐标不匹配
- 使用正则表达式查找字符串中的不匹配字符
- CSS Media Query 和 Javascript/jQuery 不匹配
- 始终在 jQuery 自动完成中显示特定选项,即使它与输入不匹配
- 如果项目不匹配,则显示变量
- 正则表达式匹配 JQM 路由器插件中的“项目”但不匹配“项目”
- Lodash 从与值数组不匹配的数组中获取项目
- 比较 2 个数组并得到这些变量不匹配
- jquery DataTable 数据格式和警告 - 添加的数据与已知列数不匹配
- Regex匹配:被空格或行首包围,但不匹配