首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >PHP preg_match正则表达式的改进

PHP preg_match正则表达式的改进
EN

Stack Overflow用户
提问于 2011-12-06 22:27:15
回答 2查看 208关注 0票数 1

你好全

我正在尝试扩大我目前在shoutbox中使用的preg_match的范围。我正在努力构建我当前的正则表达式,以获得所需的标识。请查看我正在使用的当前正则表达式,然后是一些关于我想实现的匹配的信息。

当前正则表达式:

~\bf+(?:\.+|\s+)?r+(?:\.+|\s+)?e+(?:\.+|\s+)?d+(?:\.+|)?\b~i

想要的匹配信息:

01 Lorem ipsum dolor fred同坐。

  • 识别关键词.

02 Lorem ipsum dolor $fred坐姿相同。

  • 识别单个美元符号和关键字。

03 Lorem ipsum dolor $ofred坐席。

  • 识别单个美元符号,后面跟着一个字母数字字符和关键字。

04 Lorem ipsum dolor $ooofred坐席。

  • 识别单个美元符号,后面跟着多个字母数字字符和关键字。

05 $$$ooofred坐位。

  • 识别多个美元符号,后面跟着多个字母数字字符和关键字。

06 Lorem ipsum dolor $$$ofred同坐。

  • 识别多个美元符号,后面跟着一个字母数字字符和关键字。

07 Lorem ipsum dolor $o$oo$$$ofred同坐。

  • 识别美元符号和字母数字字符的任何组合,后面跟着关键字。

08 Lorem ipsum dolor $o$oo $$$ofred

破坏identification的

  • 空间

09 $ofred也是。

无前导空间的

10 Lorem ipsum dolor $ofred

无尾随空间的

11 $ofred

  • 用尾随符号

识别

谢谢你的帮助,非常感谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-12-06 22:39:11

对于这么小的正则表达式,这一定是我见过的最长的解释:

代码语言:javascript
运行
复制
if (preg_match('/(?<=^|\s)(?:\bfred\b|\$[$\w]*fred\b)/x', $subject, $regs)) {
    $result = $regs[0];
}

解释:

代码语言:javascript
运行
复制
"
(?<=           # Assert that the regex below can be matched, with the match ending at this position (positive lookbehind)
               # Match either the regular expression below (attempting the next alternative only if this one fails)
      ^        # Assert position at the beginning of the string
   |           # Or match regular expression number 2 below (the entire group fails if this one fails to match)
      \s       # Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
)
(?:            # Match the regular expression below
               # Match either the regular expression below (attempting the next alternative only if this one fails)
      \b       # Assert position at a word boundary
      fred     # Match the characters “fred” literally
      \b       # Assert position at a word boundary
   |           # Or match regular expression number 2 below (the entire group fails if this one fails to match)
      \$       # Match the character “$” literally
      [$\w]    # Match a single character present in the list below
               # The character “$”
               # A word character (letters, digits, etc.)
         *     # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
      fred     # Match the characters “fred” literally
      \b       # Assert position at a word boundary
)
"
票数 1
EN

Stack Overflow用户

发布于 2011-12-06 22:35:46

代码语言:javascript
运行
复制
/((\$[\w\$]*)?fred)/

那个大霸王怎么了?

我不确定我是否理解:

代码语言:javascript
运行
复制
(?:\.+|\s+)

在你的领地里。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8407796

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档