Ruby 正则表达式匹配换行符后跟除(3 个大写字符后跟竖线)以外的任何内容

Ruby Regex match a newline followed by anything but (3 uppercase characters followed by a pipe)

(希望如此)这里是简单的正则表达式问题。我正在寻找匹配 1 个或多个后跟三个大写字符和竖线 (|) 的特定模式的换行符,并删除它们。

举个例子,我想转这个:

foo bar foo bar.



Normal

0

false

false

false



EN-US

JA


X-NONE




foo bar foo bar




|||||HH
OBX|156|TX|foo bar|||N
OBX|157|TX|foo bar

进入这个:

foo bar foo bar. Normal  0 false  false false  EN-US JA  X-NONE|||||HH
OBX|156|TX|foo bar|||N
OBX|157|TX|foo bar

我这里有适用于 Sublime 的正则表达式:

(\n+)(?!MSH|PID|NTE|PV1|RXO|ORC|DG1|OBR|OBX).*

但是在 ruby 中,它并没有去掉换行符。将 sublime 正则表达式转换为 rails 的正则表达式时,我遗漏了什么吗?

@r.force_encoding("UTF-8").gsub("\r\n","\r").gsub("(\r+)(?!MSH|PID|NTE|PV1|RXO|ORC|DG1|OBR|OBX)(.*)"," ")
str = <<-MULTI
foo bar foo bar.



Normal

0

false

false

false



EN-US

JA


X-NONE




foo bar foo bar




|||||HH
OBX|156|TX|foo bar|||N
OBX|157|TX|foo bar
MULTI

str.gsub(/(\n+)(?!MSH|PID|NTE|PV1|RXO|ORC|DG1|OBR|OBX).*/,'')

# It gives your desired result

我的解决方案是单独处理每一行,多行正则表达式可能会让很多人感到困惑。

.each_line 或 .lines return 单独的行。

.grep 将根据正则表达式或基于字符串的模式匹配数组。

.join 将从结果中提取单行和 return 单个多行字符串。

str.each_line
   .grep( /^[A-Z]{3,3}\|.+/ )
   .join( '' )

至于正则表达式,我们也将其分解,现在我们只是逐行处理:

^      - Starting at the beginning of the line.
[A-Z]  - Only match the range of chars from 'A' to 'Z' ( all cap chars ).
{3, 3} - Match only 3 chars, no more, no less.
\|     - Followed by a '|' char.
.+     - Followed by 1+ chars of anything.

如果 str 是你的字符串,

r = /
    \n+                        # match one or more newlines
    (?!                        # start a negative lookahead
      #{Regexp.union(keepers)} # match one of keepers
      \|                       # match pipe--escape required
    )                          # close negative lookahead 
    /x                         # extended/free-spacing regex definition mode
  #=> /
      \n+
      (?!
        (?-mix:MSH|PID|NTE|PV1|RXO|ORC|DG1|OBR|OBX)
        \|
      )
      /x 

keepers = %w[ MSH PID NTE PV1 RXO ORC DG1 OBR OBX ]
  #=> ["MSH", "PID", "NTE", "PV1", "RXO", "ORC", "DG1", "OBR", "OBX"] 

puts str.gsub(r, "")
  # foo bar foo bar.Normal0falsefalsefalseEN-USJAX-NONEfoo bar foo bar|||||HH
  # OBX|156|TX|foo bar|||N
  # OBX|157|TX|foo bar