Ruby String: how to match a Regexp from a defined

2019-06-13 16:12发布

问题:

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.