正则表达式提取子串
really struggling with this...hopefully someone can put me on the right path to a solution.
My input string is structured like this:
66-2141-A-AC107-7
I'm interested in extracting the string 'AC107' using a single regular expression. I know how to do this with other PHP string functions, but I have to do this with a regular expression.
What I need is to extract all data between the third and fourth hyphens. The structure of each section is not fixed (i.e, 66 may be 8798709 and 2141 may be 38). The presence of the number of hyphens is guaranteed (i.e., there will always be a total of four (4) hyphens).
Any help/guidance is greatly appreciated!
真的在努力解决这个问题...希望有人能让我走上解决方案的正确道路。 p>
我的输入字符串结构如下: p>
66-2141-A-AC107-7 p>
我很感兴趣 使用单个正则表达式提取字符串'AC107'。 我知道如何使用其他PHP字符串函数执行此操作,但我必须使用正则表达式执行此操作。 p>
我需要的是提取第三个和第四个连字符之间的所有数据。 每个部分的结构不是固定的(即,66可以是8798709,2141可以是38)。 保证了连字符数量的存在(即,总共会有四(4)个连字符)。 p>
非常感谢任何帮助/指导! p> \ n div>
This will do what you need:
(?:[^-]*-){3}([^-]+)
Explanation:
-
(?:[^-]*-)
Look for zero or more non-hyphen characters followed by a hyphen -
{3}
Look for three of the blocks just described -
([^-]+)
Capture all the consecutive non-hyphen characters from that point forward (will automatically cut off before the next hyphen)
You can use it in PHP like this:
$str = '66-2141-A-AC107-7';
preg_match('/^(?:[^-]*-){3}([^-]+)/', $str, $matches);
echo $matches[1]; // prints AC107
This should look for anything followed by a hyphen 3 times and then in group 2 (the second set of parenthesis) it will have your value, followed by another hyphen and anything else.
/^(.*-){3}(.*)-(.*)/
You can access it by using $2. In php, it would be like this:
$string = '66-2141-A-AC107-7';
preg_match('/^(.*-){3}(.*)-(.*)/', $string, $matches);
$special_id = $matches[2];
print $special_id;