用于在字符串之前和之后选择子字符串的正则表达式

时间:2017-05-15 14:46:34

标签: ruby regex string

我正在尝试找到一个正确的正则表达式来选择另一个子串之间的子串,我想排除它。例如,在这个字符串中:

11 - 12£ in $ + 13

我想选择12£$。基本上,它是in周围的子串,直到我点击我想用作结束/开始的值数组,在这种情况下,算术运算符%w(+ - / *)

到目前为止,我最接近的是使用此正则表达式/(.\d\p{Sc})\sin\s(\p{Sc})/

更多例子:

10 - 12$ in £ - 13$应该返回12$£

12 $ in £应该返回12$£

100£in$应该返回100£$

2 个答案:

答案 0 :(得分:2)

sentence.match(/[^-+*\/]*in[^-+*\/]*/).to_s.strip.split(/ *in */)
  • [^-+*\/]*匹配多个非算术运算符
  • 因此,这将从“打开”到围绕in
  • “关闭”运算符获取所有内容
  • #strip删除了前导和尾随空格
  • 最后,分成两个字符串,删除in及其周围的空格

答案 1 :(得分:0)

r = /
    \s+[+*\/-]\s+ # match 1+ whitespaces, 1 char in char class, 1+ whitespaces
    (\S+)         # match 1+ non-whitespaces in capture group 1
    \s+in\s+      # match 1+ whitespaces, 'in', 1+ whitespaces
    (\S+)         # match 1+ non-whitespaces in capture group 2
    \s+[+*\/-]\s  # match 1+ whitespaces, 1 char in char class, 1+ whitespaces
    /x            # free-spacing regex definition mode

str = '11 -     12£ in $ + 13 / 13F in   % * 4'
str.scan(r)
  #=> [["12£", "$"], ["13F", "%"]] 

请参阅String#scan的文档,了解scan如何处理捕获组。

请注意,'-'必须是字符类[+*\/-]中的第一个或最后一个。