regex - 我可以让我的 Alteryx RegEx 解析有条件吗?
问题描述
我收到带有以下字段的消息。我想对用户输入进行分组和提取。大多数提交的内容都包含所有字段,并且正则表达式效果很好。如果有人删除额外的行,假设他们只需要填写金额 1,就会出现问题
Name:
Number:
Amount:
Old Code:
Code 1:
Amount 1:
Code 2:
Amount 2:
Code 3:
Amount 3:
Code 4:
Amount 4:
我正在使用 Alteryx 解析消息内容并成功使用我当前的正则表达式,但希望为不可避免的用户提交不一致做好准备
Name:(.+)\sNumber:(.+)\sAmount:(.+)\sOld Code:(.+)\sCode 1:(.+)\sAmount 1:(.+)\sCode 2:(.*?)\sAmount 2:(.*?)\sCode 3:(.*?)\sAmount 3:(.*?)\sCode 4:(.*?)\sAmount 4:(.*?[^-]*)
即使删除了列出的字段,是否可以让 Alteryx 从消息中返回解析结果?
解决方案
无论如何,您始终可以围绕
行进行级联嵌套可选分组,以匹配在某一点上有效的内容。
这期望表单行是有序的。如果不是,
则需要不同类型的正则表达式 - 无序正则表达式(请参阅底部的正则表达式)。
这两个正则表达式都适用于 Perl 5.10
(?-ms)Name:(.*)(?:\s+Number:(.*)(?:\s+Amount:(.*)(?:\s+Old[ ]+Code:(.*)(?:\s+Code[ ]+1:(.*)(?:\s+Amount[ ]+1:(.*)(?:\s+Code[ ]+2:(.*)(?:\s+Amount[ ]+2:(.*)(?:\s+Code[ ]+3:(.*)(?:\s+Amount[ ]+3:(.*)(?:\s+Code[ ]+4:(.*)(?:\s+Amount[ ]+4:(.*?[^-]*))?)?)?)?)?)?)?)?)?)?)?
https://regex101.com/r/9oKXEE/1
对于乱序匹配,使用这个
(?m-s)\A(?:[\S\s]*?(?:(?(1)(?!))^\h*Name\h*:\h*(.*)|(?(2)(?!))^\h*Number\h*:\h*(.*)|(?(3)(?!))^\h*Amount\h*:\h*(.*)|(?(4)(?!))^\h*Old\h*Code\h*:\h*(.*)|(?(5)(?!))^\h*Code\h*1\h*:\h*(.*)|(?(6)(?!))^\h*Amount\h*1\h*:\h*(.*)|(?(7)(?!))^\h*Code\h*2\h*:\h*(.*)|(?(8)(?!))^\h*Amount\h*2\h*:\h*(.*)|(?(9)(?!))^\h*Code\h*3\h*:\h*(.*)|(?(10)(?!))^\h*Amount\h*3\h*:\h*(.*)|(?(11)(?!))^\h*Code\h*4\h*:\h*(.*)|(?(12)(?!))^\h*Amount\h*4\h*:\h*(.*?))){1,12}
推荐阅读
- javascript - 如何在jQuery中动画后删除元素?
- html - 为什么将窗口大小的画布元素从内联更改为块删除滚动条?
- vue.js - vue-testing-library 出现“vue-cli-service 未被识别为内部或外部命令”错误
- c - _mm_load_si128 以相反的顺序加载数据
- javascript - 为什么只执行最后一个输出语句?
- python - 函数声明中的 Python TypeError
- php - 将 htmlspecialchars_decode 与 PDO 一起用于编辑表单?
- python - Python 3.9 找不到 Python pip 模块“没有名为‘...’的模块”
- php - Lumen 8 依赖注入 - 无法解析的依赖解析 [参数 #0 [
$app ]] 在类 Illuminate\Support\ServiceProvider - python - 如何修复 ValueError:输入形状在 python 中不与栅格重叠?