将大括号占位符与可变数量的点分隔内部值相匹配
我有这样的字符串: {$foo.bar}
和 {$foo.bar.anything}
其中:foo AND bar AND everything === 字母数字
我想通过 preg_match(正则表达式)
匹配 PHP
中的上述 2 个字符串,除了那些没有任何点的字符串例如:{$foo}
I have strings like : {$foo.bar}
and {$foo.bar.anything}
WHERE : foo AND bar AND anything === alphanumeric
i want to match the above 2 strings in PHP
via preg_match(regular expression)
except those without any dot for example : {$foo}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
匹配
- 不匹配
与采用的 Joe 的 PCRE 案例 insensitive 修饰符 将其缩短一点。
特别感谢 sln 让我保持警惕,直到它完美为止。 :)
matches
does not match
Adopted Joe’s PCRE case-insensitive modifier to shorten it a bit.
Special thanks to sln for keeping me on my toes until it’s perfect. :)
您可能需要
preg_match_all
而不是preg_match
- 它会获取所有匹配项,顾名思义,而不仅仅是第一个匹配项。至于你想要的正则表达式,类似这样的东西应该可以工作
You probably want
preg_match_all
rather thanpreg_match
- it gets all matches, as the name suggests, rather than just the first one.As for the regex you want, something like this should work
假设 php regex 与 perl 相同,
这意味着以一个或多个字母数字开头,后跟
.
,后跟多个字母数字或.
。$
表示一直到字符串末尾。如果它不能以
.
结尾,那么如果不允许
..
它会变得很棘手,因为正则表达式引擎无法处理指定多字符子表达式的重复。但如果你的,我认为它是这样的这意味着以一个或多个字母数字开头,后跟一个或多个重复
.
后跟一个或多个字母数字。$
表示一直到字符串末尾。Assuming php regex is the same as perl
That means starting with one or more alphanumeric, followed by a
.
, followed by a number of alphanumerics or.
. The$
means all the way to the end of the string.If it cannot end with a
.
thenIf
..
is not allowed It gets tricker as not ell regex engines handle specifying repetitions of multi char sub expressions. But if your's does I think its something likeThat means starting with one or more alphanumeric, followed one or more repetions of by a
.
followed one or more alphanumerics. The$
means all the way to the end of the string.第一个匹配
{$
。然后匹配任何字母数字字符串。然后匹配以.
开头的任何字母数字字符串。然后匹配}
。First match
{$
. Then match any alphanumeric string. Then match any alphanumeric strings beginning with.
. Then match}
.因此,您首先匹配 foo 和一个点
{$foo.
,然后是可选的任何字符和点{$foo.bar.
,最后是另一个字符串。{$foo.bar.anything}
So you first match foo and a dot
{$foo.
, then optionally any characters and dots{$foo.bar.
, and finally another string of characters.{$foo.bar.anything}
这是我对问题的解决方案,根据您确切想要提取的内容,有一些替代方案。
{$aaa.bbb[.ccc[.ddd ...]]}
内容 bbb} 事物(例如aaa.bbb
){$aaa}
或{$aaa.bbb.ccc.ddd}
)。代码:
This is my solution to the problem, with some alternatives depending on what you exactly want to extract.
{$aaa.bbb[.ccc[.ddd ...]]}
thing, provided that it contains at least one dot{$aaa.bbb}
thing (eg.aaa.bbb
){$aaa}
or{$aaa.bbb.ccc.ddd}
).Code: