Ruby String: how to match a Regexp from a defined position

蹲街弑〆低调 提交于 2019-12-23 05:14:00

问题


I want to match a regexp from a ruby string only from a defined position. Matches before that position do not interest me. Moreover, I'd like \A to match this position.

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. If the match is not exactly at position index, it return nil.

Is there a more elegant way to do this (I want to avoid to create the temporary string with the first slice)?

Thanks


回答1:


You could use ^.{#{index}} inside the regular expression. 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? 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. When index = 4, it will check if there's 4 characters from the beginning. Then it will check your own regular expression and only return true if yours is valid as well. 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.



来源:https://stackoverflow.com/questions/7292976/ruby-string-how-to-match-a-regexp-from-a-defined-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!