在可选模式处停止正则表达式搜索
Stop regex search at optional pattern
我正在尝试制作一个可以从电子邮件中提取一些元素的正则表达式模式。电子邮件可能会转发,也可能不会转发。如果不转发,会匹配这个格式:
-match one
-match two
-match three
-and a bunch of notes here, potentially with more than 1 line or newlines included
and there may be hyphens in this text as well
如果转发的话会匹配这个格式:
-match one
-match two
-match three
-and a bunch of notes here, potentially with more than 1 line or newlines included
and there may be hyphens in this text as well
---------- Forwarded message ----------
From:....
我在制作适用于这两种情况的模式时遇到问题,并且会捕获第 4 个破折号和以“------已转发...”开头的行之间的所有内容。
这是我想出的作为占位符的模式:\-\s?(.+)\s\-\s?(.+)\s\-\s?(.+)\s\-\s?([^[-]*)
。但是,当第 4 个破折号后的文本中有连字符时,这不起作用,因为它会在找到连字符后切断。
一个选项可能是匹配 3 行并且只匹配第四行的破折号。然后将所有不以破折号开头的行捕获到一个组中。
^(?:-.*\n){3}-((?:.*\n(?!-).*)*)
^
字符串开头
(?:-.*\n){3}
匹配 3 行和一个换行符(使用 (?:-.*\n)+
匹配 1 行或多行)
-
匹配第四个破折号
(
捕获 组 1
(?:.*\n(?!-).*)*
匹配所有不以破折号开头的行
)
关闭组 1
如果没有重叠,您也可以排除匹配---------- Forwarded message
^(?:-.*\n){3}-((?:.*\n(?!-+ Forwarded message).*)*)
但是看看this example在那种情况下所有的匹配项也可以是什么。
我正在尝试制作一个可以从电子邮件中提取一些元素的正则表达式模式。电子邮件可能会转发,也可能不会转发。如果不转发,会匹配这个格式:
-match one
-match two
-match three
-and a bunch of notes here, potentially with more than 1 line or newlines included
and there may be hyphens in this text as well
如果转发的话会匹配这个格式:
-match one
-match two
-match three
-and a bunch of notes here, potentially with more than 1 line or newlines included
and there may be hyphens in this text as well
---------- Forwarded message ----------
From:....
我在制作适用于这两种情况的模式时遇到问题,并且会捕获第 4 个破折号和以“------已转发...”开头的行之间的所有内容。
这是我想出的作为占位符的模式:\-\s?(.+)\s\-\s?(.+)\s\-\s?(.+)\s\-\s?([^[-]*)
。但是,当第 4 个破折号后的文本中有连字符时,这不起作用,因为它会在找到连字符后切断。
一个选项可能是匹配 3 行并且只匹配第四行的破折号。然后将所有不以破折号开头的行捕获到一个组中。
^(?:-.*\n){3}-((?:.*\n(?!-).*)*)
^
字符串开头(?:-.*\n){3}
匹配 3 行和一个换行符(使用(?:-.*\n)+
匹配 1 行或多行)-
匹配第四个破折号(
捕获 组 1(?:.*\n(?!-).*)*
匹配所有不以破折号开头的行
)
关闭组 1
如果没有重叠,您也可以排除匹配---------- Forwarded message
^(?:-.*\n){3}-((?:.*\n(?!-+ Forwarded message).*)*)
但是看看this example在那种情况下所有的匹配项也可以是什么。