首页 > 解决方案 > 正则表达式 - 找到可能的最短匹配

问题描述

问题

鉴于以下情况:

\plain\f2 This is the first part of the note. This is the second part of the note. This is the \plain\f2\fs24\cf6{\txfielddef{\*\txfieldstart\txfieldtype1\txfieldflags144\txfielddataval44334\txfielddata 35003800380039000000}{\*\txfielddatadef\txfielddatatype1\txfielddata 340034003300330034000000}{\*\txfieldtext 20{\*\txfieldend}}{\field{\*\fldinst{ HYPERLINK "44334" }}{\fldrslt{20}}}}\plain\f2\fs24 part of the note.

我想制作这个:

\plain\f2 This is the first part of the note. This is the second part of the note. This is the third part of the note.

我试过的

示例输入/输出是我需要解析的数据的一个非常简化的版本,如果有一种以编程方式解析数据的方法,那就太好了。我有一个 PHP 应用程序,我一直在尝试使用正则表达式来匹配重要的段,然后过滤掉不需要的字符串部分。到目前为止,这是我想出的:

/\\plain.*?\\field{\\\*\\fldinst{ HYPERLINK "(.*?)" }}{\\fldrslt{(.*?)}}}}\\plain.*? /gm

正则表达式101: https ://regex101.com/r/ILLZU6/2

它几乎与我想要的匹配,但它抓住了最长的匹配而不是最短的匹配。我希望它只匹配\\plain. \\field{...也许在 之后\\plain,我可以匹配除空格之外的任何内容?我该怎么做呢?

我不是正则表达式专家,但我的用例确实需要它。(否则,我只会编写代码来处理所有事情。)任何帮助将不胜感激!

标签: regex

解决方案


(?:(?!\\plain).)*将匹配任何字符串,除非它包含\\plain. 这是实现这一点的正则表达式:

/\\plain(?:(?!\\plain).)*\\field{\\\*\\fldinst{ HYPERLINK "(.*?)" }}{\\fldrslt{(.*?)}}}}\\plain.*? /gm

正则表达式101: https ://regex101.com/r/ILLZU6/5


此外,(?: |$)如果您想允许文本的结尾以及空格触发它,您可以将结尾的空格替换为:

/\\plain(?:(?!\\plain).)*\\field{\\\*\\fldinst{ HYPERLINK "(.*?)" }}{\\fldrslt{(.*?)}}}}\\plain.*?(?: |$)/gm

正则表达式101: https ://regex101.com/r/ILLZU6/4


推荐阅读