簡體   English   中英

正則表達式 / Ruby - 拆分保持分隔符

[英]Regex / Ruby - split keeping delimiter

我需要拆分包含變量/分隔符的字符串,例如;

“您好 %Customer Name% 您的訂單號是 %Order Number% 並將很快發貨”

使用;

string.split(/%/)
=> ["Hello ", "Customer Name", " your order number is ", "Order Number", " and will be delivered soon"]

這接近要求,但我正在努力達到;

["Hello ", "%Customer Name%", " your order number is ", "%Order Number%", " and will be delivered soon"]

所以基本上我需要在 % 處拆分,但將其保留在返回的字段中。 我已經嘗試使用正則表達式向前/向后看,但不能完全正確。

您可以將String#split與類似的模式一起使用

/(%[^%]*%)/

根據文檔:

如果pattern包含組,則相應的匹配項也將在數組中返回。

請參閱正則表達式演示,它匹配並捕獲到第 1 組一個%字符,然后是除%之外的任何 0 個或更多字符,然后是一個%

請參閱Ruby 演示

s = "Hello %Customer Name% your order number is %Order Number% and will be delivered soon"
p s.split(/(%[^%]*%)/)
# => ["Hello ", "%Customer Name%", " your order number is ", "%Order Number%", " and will be delivered soon"]

以下是可以完成的三種方式。

str = "%Hello% dear %Cust Name% %your order %Order Nbr% was %lost%"

1.使用字符串#split

r = /
    (?<=     # begin positive lookbehind
      \A     # match beginning of string
      |      # or
      [ ]    # match a space
    )        # end positive lookbehind
    (?=%)    # positive lookahead asserts next char is '%'
    |        # or
    (?<=%)   # positive lookbehind asserts previous char is '%'
    (?=      # begin a positive lookahead
      [ ]    # match a space
      |      # or
      \z     # match end of string
    )        # end positive lookahead
    /x       # free-spacing regex definition mode

str.split r
  #=> ["%Hello%", " dear ", "%Cust Name%", " ", "%your%", " order ",
  #    "%Order Nbr%", " was ", "%lost%"]

2.使用字符串#scan

r = /
    %[^%]*%       # match '%', 0+ chars other than '%', '%' 
    |             # or
    (?:           # begin non-capture group#
      (?<=\A)     # positive lookbehind asserts at beginning of string
      |           # or
      (?<=%)      # positive lookbehind asserts previous char is '%'
      (?=[ ])     # positive lookahead asserts next char is a space
    )             # end non-capture group
    [^%]*         # match 0+ chars other than '%' 
    (?=           # begin positive lookahead
      \z          # match end of string
      |           # or
      (?<=[ ])    # assert previous char is a space
      %           # match '%'
    )             # end positive lookahead
    /x            # free-spacing regex definition mode

str.scan r 
  #=> ["%Hello%", " dear ", "%Cust Name%", " ", "%your%", " order ",
  #    "%Order Nbr%", " was ", "%lost%"] 

3. 使用Enumerable#slice_when

str.each_char.slice_when { |a,b|
  (a == ' ') & (b == '%') || (a == '%') & (b == ' ') }.map(&:join)
  #=> ["%Hello%", " dear ", "%Cust Name%", " ", "%your%", " order ",
  #    "%Order Nbr%", " was ", "%lost%"]    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM