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.
How about below using StringScanner
?
require 'strscan'
scanner = StringScanner.new 'xay'
scanner.pos = 1
!!scanner.scan(/a/) # => true
scanner = StringScanner.new 'xnnay'
scanner.pos = 1
!!scanner.scan(/a/) # => false
Regexp#match
has an optional second parameter pos
, but it works like Python's search
method. You could however check if the returned MatchData
begins at the specified position:
re = /a/
match_data = re.match('xay', 1)
match_data.begin(0) == 1
#=> true
match_data = re.match('xhay', 1)
match_data.begin(0) == 1
#=> false
match_data = re.match('áay', 1)
match_data.begin(0) == 1
#=> true
match_data = re.match('aay', 1)
match_data.begin(0) == 1
#=> true
Extending a little bit on what @sunbabaphu answered:
def matching_at_pos(x=0, regex)
/\A.{#{x-1}}#{regex}/
end # note the position is 1 indexed
'xxa' =~ matching_at_pos(2, /a/)
=> nil
'xxa' =~ matching_at_pos(3, /a/)
=> 0
'xxa' =~ matching_at_pos(4, /a/)
=> nil
The answer to this question is \G
.
\G
matches the starting point of the regex match, when calling the two-argument version of String#match
that takes a starting position.
'xay'.match(/\Ga/, 1) # match because /a/ starts at 1
'xhay'match(/\Ga/, 1) # no match because character at 1 is 'h'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.