【问题标题】:regex to match up to first occurrence of正则表达式匹配第一次出现
【发布时间】:2016-03-18 16:51:15
【问题描述】:

我有这段文字:

{{Infobox Item
|name = value
|prop2 = value
|prop3 = value
}}

它来自一个 mediawiki 模板。

我有以下正则表达式:

preg_match('/\{\{Infobox Item.+\\n\}\}\\n/s', $text, $ra);

我正在使用 PHP。

我想匹配从{{Infobox Item 到第一次出现的}},它总是会单独出现在一行上。上面的正则表达式将从{{Infobox Item 匹配到另一个{{ }} 样式块的末尾,这不是我想要的。我怎样才能做到这一点?

【问题讨论】:

标签: php regex mediawiki-templates


【解决方案1】:

代码

preg_match('/{{Infobox Item.+?^}}$/sm', $subject, $regs)

正则表达式

{{Infobox Item.+?^}}$

https://regex101.com/r/gC0oV1/1

人类可读

# {{Infobox Item.+?^}}$
# 
# Options: Case sensitive; Exact spacing; Dot matches line breaks; ^$ match at line breaks; Greedy quantifiers
# 
# Match the character string “{{Infobox Item” literally (case sensitive) «{{Infobox Item»
# Match any single character «.+?»
#    Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»
# Assert position at the beginning of a line (at beginning of the string or after a line break character) (line feed) «^»
# Match the character string “}}” literally «}}»
# Assert position at the end of a line (at the end of the string or before a line break character) (line feed) «$»

【讨论】:

  • }} 不是文件中的最后一行,这是我的主要问题。文件中还有其他内容以及其他 {{Infobox whatever }} 样式块。我只想要这些块中的第一个。
  • 这不需要}} 在最后一行。
  • 注意/m限定词的使用——改变^和$的含义。
  • nvm 院长,这行得通。问题出在我的其他代码上。如果我发现一行没有“prop = val”,我就退出了。有一行只有 |prop 导致事情中断。抱歉
猜你喜欢
  • 2018-06-28
  • 2022-08-13
  • 2015-04-10
  • 1970-01-01
  • 1970-01-01
  • 2011-01-02
  • 2019-07-19
相关资源
最近更新 更多