简体   繁体   中英

How can I match the second occurrence of a character with a regular expression?

I'm trying to match the second forward-slash in a relative URL.

/dir/entry

I want to match the / following dir .

如果您试图分解路径中的目录,将正则表达式保留在工具箱中并使用explode()可能是有意义的。

$parts = explode( '/', $path );

Since there is no significance about the / , I assume you want to find out the position. You can do it with the fourth parameter of preg_match_all :

preg_match_all('~/~', $input, $matches, PREG_OFFSET_CAPTURE);
$pos = $matches[0][1][1];

The indexing into $matches is quite horrible, though. The first index corresponds to the capture. 0 is the whole match, 1 , 2 , 3 and so on would be the results of capturing groups (sets of parentheses inside the pattern), which you don't have here. The second index corresponds to the match. You want the second match, so you want to go for index 1 . The last index is 0 for the actually matched/captured string and 1 for the match's/capture's offset.

Do you want to match the second slash and nothing else? Try this:

preg_match('~^/[^/]+\K/~', '/dir/entry');

\\K is the MATCH POINT RESET construct: when it's encountered, the regex engine "forgets" whatever characters it's seen so far, and acts like the current match position is the beginning of the match. For example, if you wanted to replace the second slash with @ , you would normally do this:

preg_replace('~^(/[^/]+)/~', '$1@', '/dir/entry');  # /dir@entry

But if you're in a situation where you can't use a capturing group, \\K will set you right:

preg_replace('~^/[^/]+\K/~', '@', '/dir/entry');  # /dir@entry

\\K is only supported in Perl and PHP that I know of.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM