문제

I want to match the string a but I want my capture patten to be b.

To capture a named as id I can easily do:

(?<id>a)

but I want id to be b when the original string was just a. i.e I want the capture to be characters that aren't in the original string.

For example, in PHP it would look something like:

preg_match('/your_magic/', 'a', $matches);
print $matches['id'] == 'b'; // true
도움이 되었습니까?

해결책

There is no way to get anything in to a capturing group which isn't in the input string. Capturing groups are (at least in Perl) partially represented as start/end positions of the original input string.

If the value you want the capturing group to get is in the input string you can do that using lookarounds. The desired string has to be after the match if your regex flavor has a limited lookbehind (like PHP).

For example:

preg_match('/a(?=.*(?<id>b))/', 'a foo b', $matches);
print "matched '$matches[0]', id is '$matches[id]'";

Output:

matched 'a', id is 'b'
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top