【问题标题】:Skip first occurrence of semicolon using regex使用正则表达式跳过第一次出现的分号
【发布时间】:2016-01-26 21:11:33
【问题描述】:

我正在尝试跳过字符串中的第一个分号,并使用正则表达式对分号的其余部分进行拆分:

lines = </li> <li> Urinary tract infection </li> <li> Respiratory infection </li> <li> Sinus problems; and </li> <li> Ear infections; <li> Some more info </li>

我正在使用此代码在除第一个分号之外的每个分号处拆分它:

lines.split(/(?<!\\\\);/)

我的预期输出是:

["</li> <li> Urinary tract infection </li> <li> Respiratory infection </li> <li> Sinus problems; and </li> <li> Ear infections","<li> Some more info </li>" ]

请注意,字符串可以很长,包含任意数量的分号,但我想防止仅从第一个分号开始拆分。

【问题讨论】:

  • this demo - 但是,它在最后一个分号处被分割。
  • @WiktorStribiżew 感谢您的快速响应。我发布的字符串只是一个示例。我工作的原始字符串太长并且有多个分号。所以我只想跳过第一个半冒号并考虑所有半冒号。我刚刚更新了问题
  • this demo 怎么样? lines.scan(/\A[^;]*;[^;]*|[^;]+/)?
  • 这看起来像是一个 XY 问题。分裂的目标是什么?为什么不使用解析器,例如 Nokogiri,因为您正在尝试操作 HTML。在处理 XML/HTML 文本时,正则表达式很快就会崩溃。

标签: ruby-on-rails ruby regex ruby-on-rails-3 ruby-on-rails-3.2


【解决方案1】:

我必须使用正则表达式吗?

str = "Now is; the time; for all good; people; to party" 

f, sc, l = str.partition(';')
af, *a = str[str.index(';')+1..-1].split(';')
[f+sc+af, *a]
  #=> ["Now is; the time", " for all good", " people", " to party"] 

步骤:

f, sc, l = str.partition(';')
   #=> ["Now is", ";", " the time; for all good; people; to party"] 
f  #=> "Now is" 
sc #=> ";" 
l  #=> " the time; for all good; people; to party" 
idx = str.index(';')+1
   #=> 7 
b = str[idx..-1]
   #=> " the time; for all good; people; to party" 
af, *a = b.split(';')
af #=> " the time" 
a  #=> [" for all good", " people", " to party"] 
[f+sc+af, *a]
   #=> ["Now is; the time", " for all good", " people", " to party"] 

以 OP 为例:

f, sc, l = lines.partition(';')
af, *a = lines[lines.index(';')+1..-1].split(';')
[f+sc+af, *a]
  #=> ["</li> <li> Urinary tract infection </li> <li> Respiratory infection\    
         </li> <li> Sinus problems; and </li> <li> Ear infections",
  #    " <li> Some more info </li>"]

另一种方式:

b = str.sub(';', 0.chr).split(';')
  #=> ["Now is\u0000 the time", " for all good", " people", " to party"] 
a[0].sub!(0.chr, ';')
  #=> "Now is; the time" 
a #=> ["Now is; the time", " for all good", " people", " to party"] 

【讨论】:

  • 这是否意味着您假设结果中会有特定数量的元素?
  • @Wikor,我的理解(我相信这与 OP 示例的预期结果一致)是字符串将在分号上拆分,除了第一个分号被跳过,使其成为返回数组的第一个元素(字符串)的字符。没有?
  • 好吧,我只是反对仅代码的答案。代码上的一些 cmets 会有很大帮助。
  • @CarySwoveland 我使用正则表达式的原因是因为涉及到 HTML。在处理空格和特殊字符时,我让我的生活更轻松。我想出了一个类似的代码,但它似乎不适合我正在使用的系统。所以我特别需要使用正则表达式来完成这项工作。我希望你能理解我的意思。
  • @Wiktor,我通常会提供解释(有时会过火),但在这里我认为显示每个语句返回的内容就足够了。不过我会补充一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-18
  • 2022-08-13
  • 2018-06-28
  • 1970-01-01
  • 2014-12-15
相关资源
最近更新 更多