我正在尝试找到一个正确的正则表达式来选择另一个子串之间的子串,我想排除它。例如,在这个字符串中:
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£
和$
答案 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
如何处理捕获组。
请注意,'-'
必须是字符类[+*\/-]
中的第一个或最后一个。