I have a reqular expression for getting sub-string from a string, if a particular string doesn't exist then try to get another sub-string.
我有一个reqular表达式,用于从字符串中获取子字符串,如果某个特定字符串不存在,则尝试获取另一个子字符串。
Reqular expression i am trying is this:
我正在尝试的Reqular表达式是这样的:
\@\s*\((.*?)\)|\((.*?)\)
But this does not work, and always get the second option sub-string instead of the first option.
但这不起作用,并始终获得第二个选项子字符串而不是第一个选项。
Example string is
示例字符串是
some text (2nd Sub-string) @ (First sub-string)
一些文字(第二个子串)@(第一个子串)
And it give me this result:
它给了我这个结果:
Array
(
[0] => (2nd Sub-string)
[1] =>
[2] => 2nd Sub-string
)
1 个解决方案
#1
1
Why don't you simply get both strings (for which your regexp works correctly) and check their existence programmatically? Something like:
为什么不简单地获取两个字符串(正则表达式正常工作)并以编程方式检查它们的存在?就像是:
$num = preg_match_all(
"/\@\s*\((.*?)\)|\((.*?)\)/",
"some text (2nd Sub-string) @ (First sub-string)",
$matches, PREG_SET_ORDER
);
var_dump($num, $matches);
if($num < 2)
{
// no second match, read first
}
if(!array_key_exists(2, $matches[1]))
{
// another way to put it
}
HTH.
#1
1
Why don't you simply get both strings (for which your regexp works correctly) and check their existence programmatically? Something like:
为什么不简单地获取两个字符串(正则表达式正常工作)并以编程方式检查它们的存在?就像是:
$num = preg_match_all(
"/\@\s*\((.*?)\)|\((.*?)\)/",
"some text (2nd Sub-string) @ (First sub-string)",
$matches, PREG_SET_ORDER
);
var_dump($num, $matches);
if($num < 2)
{
// no second match, read first
}
if(!array_key_exists(2, $matches[1]))
{
// another way to put it
}
HTH.