问题描述
这是 Ruby 1.8.7 ,但应与1.9.x相同
This is Ruby 1.8.7 but should be same as for 1.9.x
例如,我正在尝试分割字符串:
I am trying to split a string for example:
a = "foo.bar.size.split('.').last"
# trying to split into ["foo", "bar","split('.')","last"]
基本上将其拆分为代表的命令,我正在尝试使用Regexp进行操作,但不确定如何使用regexp
Basically splitting it in commands it represents, I am trying to do it with Regexp but not sure how, idea was to use regexp
a.split(/[a-z\(\)](\.)[a-z\(\)]/)
这里尝试使用组(\.)
对其进行拆分,但这似乎不是一个好方法.
Here trying to use group (\.)
to split it with but this seems not to be good approach.
推荐答案
我认为这可以做到:
a.split(/\.(?=[\w])/)
我不知道您对正则表达式有多少了解,但是(?=[\w])
是一个前瞻性提示,仅当下一个字符是字母类型的字符时才匹配点".提前查找实际上不会获取与之匹配的文本.它只是看起来".因此,结果恰好是您要寻找的东西:
I don't know how much you know about regex, but the (?=[\w])
is a lookahead that says "only match the dot if the next character is a letter kind of character". A lookahead won't actually grab the text it matches. It just "looks". So the result is exactly what you're looking for:
> a.split(/\.(?=[\w])/)
=> ["foo", "bar", "size", "split('.')", "last"]
这篇关于Ruby String用正则表达式拆分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!