【问题标题】:RegEx for Removing First Two Segments and Leaving the Last Two Segments用于删除前两个段并保留最后两个段的正则表达式
【发布时间】:2021-08-27 13:25:34
【问题描述】:

我正在与第三方系统合作,该系统将采用正则表达式来解析其系统中的数据。我已经很多年没有写过正则表达式了,我被困住了。原始数据均以 2 或 3 个字符(建筑物)开头,然后是空格破折号空格,然后是另外 2 或 3 个字符(部门),然后是空格破折号空格,用户的全名,空格破折号空格,最后是他们的电话延期。我想以用户的全名、空格破折号和他们的扩展名结束。

系统中字段的最大字符分配为 26 个字符。如果可能的话,我宁愿修剪名字也不愿切断 4 位数的扩展名。

所有数据各不相同,但看起来与这些示例相似。

RB - HS - John Doe - 8400
MCH - SOC - Jane Smith - 5200

我需要数据看起来像:

John Doe - 8400
Jane Smith - 5200

【问题讨论】:

  • 系统是否允许您使用捕获编写某种替换操作?
  • @rici 不,这只是一个匹配选项

标签: regex parsing


【解决方案1】:

使用

Find: ^.* - (.{1,19}).*?( - [0-9]{4})$
Replace: $1$2

regex proof

解释

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  .*                       any character except \n (0 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
   -                       ' - '
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    .{1,19}                  any character except \n (between 1 and
                             19 times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  .*?                      any character except \n (0 or more times
                           (matching the least amount possible))
--------------------------------------------------------------------------------
  (                        group and capture to \2:
--------------------------------------------------------------------------------
     -                       ' - '
--------------------------------------------------------------------------------
    [0-9]{4}                 any character of: '0' to '9' (4 times)
--------------------------------------------------------------------------------
  )                        end of \2
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

【讨论】:

  • 这是一个不错的选择,但是它不允许我使用替换/替换选项。我需要使用匹配选项。我一直在玩 Branch Reset Groups,但无法正确设置。
  • @WCIT 没有办法通过分支重置组来实现这一点。那你就永远卡住了。
猜你喜欢
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-02
  • 2016-03-30
  • 2013-06-26
相关资源
最近更新 更多