如何在字符串中找到正则表达式匹配的索引? [英] How do I find the index of a regex match in a string?

查看:426
本文介绍了如何在字符串中找到正则表达式匹配的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在php中,查找和捕获与给定正则表达式匹配的所有子字符串是相当简单的,但是有没有一种简单的方法来查找字符串中第一个正则表达式匹配项的索引?

In php, it's fairly simple to find and capture all substrings that match a given regex, but is there a simple way to find the index of the first regex match in a string?

即我想要这样的东西:

$str = "123456789abcdefgh";
$index = preg_index("#abcd#", $str);
// $index == 9

推荐答案

PREG_OFFSET_CAPTURE标志与

上面的[0]对应于您要为其索引的正则表达式内的捕获组(整个表达式为0,如果存在第一个捕获组,则为1,等等),而[1]是一个记录的固定索引.

The [0] above corresponds to the capture group inside the regex whose index you want (0 for the whole expression, 1 for the first capturing group if it exists, etc) while the [1] is a fixed index, as documented.

:添加了if以使代码更易于呈现,现在并不需要理会模式一定会匹配.

Added an if to make the code more presentable, it now doesn't take for granted that the pattern will definitely match.

查看实际效果 .

See it in action.

这篇关于如何在字符串中找到正则表达式匹配的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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