Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby regex match starting at specific position

Tags:

regex

ruby

In Python I can do this:

import re
regex = re.compile('a')

regex.match('xay',1)  # match because string starts with 'a' at 1
regex.match('xhay',1) # no match because character at 1 is 'h'

However in Ruby, the match method seems to match everything past the positional argument. For instance, /a/.match('xhay',1) will return a match, even though the match actually starts at 2. However, I want to only consider matches that start at a specific position.

How do I get a similar mechanism in Ruby? I would like to match patterns that start at a specific position in the string as I can in Python.

like image 758
math4tots Avatar asked Feb 21 '26 15:02

math4tots


1 Answers

/^.{1}a/

for matching a at location x+1 in the string

/^.{x}a/

--> DEMO

like image 78
sunbabaphu Avatar answered Feb 24 '26 08:02

sunbabaphu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!