regex - 正则表达式 - 找到可能的最短匹配
问题描述
问题
鉴于以下情况:
\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
,我可以匹配除空格之外的任何内容?我该怎么做呢?
我不是正则表达式专家,但我的用例确实需要它。(否则,我只会编写代码来处理所有事情。)任何帮助将不胜感激!
解决方案
(?:(?!\\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
推荐阅读
- javascript - 以 'u' 为前缀的 API 响应数组数据
- azure - 在 Java 中为 Azure 客户端(SDK 版本-1.0.0-beta2)配置代理
- python - 基于列索引的 sort_values
- sql - SQL - 使用别名对值进行分组
- angular - 将数据从一个组件传递到多个组件的有效方法是什么?
- python - Django 测试:self.client.post 没有被第二次执行
- jquery - JQuery 中的默认选项/组合框
- ios - UITableView 中带有 NSFetchedResultsController 的附加部分
- excel - VBA从存储过程中获取输出参数
- apache-spark - 如何在使用火花数据帧比较 2 个文本文件时检查 NULL 值