regex - 在模式匹配正则表达式中使用“或”
问题描述
我正在使用正则表达式来查找匹配的模式。但不知何故,我无法找到所有的 Occrences。
我需要匹配模式的输入文件(请注意,这是一个示例文件,实际上只有 3 次出现 - 它有多个出现):
aaa-233- hi, how are you?
aaa-234- 6(-8989)
aaa-235- 123
end
所以,我希望我的输出是
hi, how are you?
6(-8988)
123
我的正则表达式是
aaa\\-[A-Za-z0-9,->#]\\-(.+?)(aaa)
伪代码
Output= matcher.group(2);
如何使逻辑从 aaa 开始读取并结束它遇到 aaa 或结束。
解决方案
采用
(?sm)^aaa-[^-]+-.*?(?=\naaa|\nend|\z)
见证明
解释
EXPLANATION
--------------------------------------------------------------------------------
(?ms) set flags for this block (with ^ and $
matching start and end of line) (with .
matching \n) (case-sensitive) (matching
whitespace and # normally)
--------------------------------------------------------------------------------
^ the beginning of a "line"
--------------------------------------------------------------------------------
aaa- 'aaa-'
--------------------------------------------------------------------------------
[^-]+ any character except: '-' (1 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
- '-'
--------------------------------------------------------------------------------
.*? any character (0 or more times (matching
the least amount possible))
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
\n '\n' (newline)
--------------------------------------------------------------------------------
aaa 'aaa'
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
\n '\n' (newline)
--------------------------------------------------------------------------------
end 'end'
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
\z the end of the string
--------------------------------------------------------------------------------
) end of look-ahead
推荐阅读
- apache - Spring Boot 中 IBM MQ 的连接池
- big-o - 使用量化定义证明多项式的 Big theta
- c++ - 当我将代码提交给在线法官时,LDBL_MAX 和 LDBL_MIN 返回错误答案
- firebase - 我想在 Firebase 数据库上将一个值设置为 True 一段时间
- php - Doctrine Join 的结果数据结构
- javascript - JavaScript - 在 Jest 测试中无法获取 jsdom 文档
- javascript - 如何在 nuxt.js 中使用 webpack 加载器?
- unity3d - 如何统一使用滑块控制 3D 对象的动画
- java - HttpServletResponse bean注入到mvc中的bean
- arrays - 在 Ruby 中查找字符串中的多个模式