[英]Ruby String: how to match a Regexp from a defined position
I want to match a regexp from a ruby string only from a defined position. 我想仅从定义的位置匹配来自ruby字符串的正则表达式。 Matches before that position do not interest me.
在那个位置之前的比赛对我不感兴趣。 Moreover, I'd like
\\A
to match this position. 而且,我想要
\\A
匹配这个位置。
I found this solution: 我发现这个解决方案:
code[index..-1][/\A[a-z_][a-zA-Z0-9_]*/]
This match the regexp at position index
in the string code
. 这匹配字符串
code
中位置index
的正则表达式。 If the match is not exactly at position index
, it return nil
. 如果匹配不完全在位置
index
,则返回nil
。
Is there a more elegant way to do this (I want to avoid to create the temporary string with the first slice)? 有没有更优雅的方法来做到这一点(我想避免用第一个切片创建临时字符串)?
Thanks 谢谢
You could use ^.{#{index}}
inside the regular expression. 您可以在正则表达式中使用
^.{#{index}}
。 Don't know if that's what you want, because I don't understand your question completely. 不知道那是不是你想要的,因为我完全不理解你的问题。 Can you maybe add an example with the tested String?
你可以用测试的字符串添加一个例子吗? And have you heard of Rubular ?
你听说过Rubular吗? Great way to test your regular expressions.
测试正则表达式的好方法。
This is how you could do it if I understand your question correctly: 如果我正确理解你的问题,你可以这样做:
code.match(/^.{#{index}}your_regex_here/)
The index
variable will be put inside your regular expression. index
变量将放在正则表达式中。 When index = 4
, it will check if there's 4 characters from the beginning. 当
index = 4
,它将检查从头开始是否有4个字符。 Then it will check your own regular expression and only return true if yours is valid as well. 然后它将检查您自己的正则表达式,并且只有在您的正则表达式有效时才返回true。 I hope it helps.
我希望它有所帮助。 Good luck.
祝好运。
EDIT 编辑
And if you want to get the matched value for your regular expression: 如果您想获得正则表达式的匹配值:
code.scan(/^.{#{index}}([a-z_][a-zA-Z0-9_]*)/).join
It puts the matched result (inside the brackets) in an Array and joins it into a String. 它将匹配的结果(在括号内)放入一个数组中并将其连接成一个String。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.