Domanda

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
È stato utile?

Soluzione

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'
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top