首页 > 解决方案 > 正则表达式在一行特殊字符之前分隔组

问题描述

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
This PM was sent by [ helloworld ] hellworld@gmail.com,
Membership Status : YES
http://gg.com.zz/US?id=gg@1

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-
Title           : Testing is testing
Quantity        : 44
Price           : 55.00
Item Location   : United States

*******************************************************************


I want this message right here, hello there, you help is deeply 
**
appreciated :)

  *** This email was sent using gg.gg.com ***

以上将是我的输出字符串,我希望在长^^^^^^-******分隔符之间获得组,

最终结果将是:

This PM was sent by [ helloworld ] hellworld@gmail.com,
Membership Status : YES
http://gg.com.zz/US?id=gg@1
Title           : Testing is testing
Quantity        : 44
Price           : 55.00
Item Location   : United States
I want this message right here, hello there, you help is deeply 
**^
appreciated :)

我试过(?<=^)[^\^]*|[^\^-]*(?<=\*\*)但无法匹配整个长^^^^^^^分隔线,有人可以帮我吗?

标签: iosregex

解决方案


您可以使用此正则表达式来捕获您的预期数据,

(?s)^(?:\^+-|\*{3,})\s*(.+?)(?=\s*(?:\^+|\*{3,}))

解释:

  • (?s)- 允许.匹配此处所需的换行符,因为要捕获的数据跨越多行
  • ^- 匹配文本的开头
  • (?:\^+-|\*{3,})\s*- 匹配一个或多个^以或三个结尾的字符-(为什么是三个,所以最后一行不匹配,因为它有 2 个星)或多个*字符,后跟可选的空格
  • (.+?)- 匹配预期的文本并在第一个分组模式中捕获它
  • (?=\s*(?:\^+|\*{3,}))- 向前看以确保它停止捕获数据,然后是可选的空格和上面的模式,如^^^^^-*****

虽然我之前的回答也有效,但这更好,因为它巧妙地捕获了数据。

演示


推荐阅读