[英]Ruby - Find REGEX match position and w the losest match apply the regex?
[英]Ruby regex match starting at specific position
在 Python 中,我可以这样做:
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'
然而在 Ruby 中, match
方法似乎匹配位置参数之后的所有内容。 例如,/a/.match( /a/.match('xhay',1)
将返回一个匹配项,即使该匹配项实际上从 2 开始。但是,我只想考虑从特定 position 开始的匹配项。
我如何在Ruby中获得类似的机制? 我想匹配字符串中以特定 position 开头的模式,就像我可以在 Python 中那样。
下面怎么用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
有一个可选的第二个参数pos
,但它的工作方式与Python的search
方法类似。 但是,您可以检查返回的MatchData
从指定位置开始:
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
在@sunbabaphu回答的问题上稍微扩展一下:
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
这个问题的答案是\G
。
\G
匹配正则表达式匹配的起点,当调用以 position 为起点的String#match
的双参数版本时。
'xay'.match(/\Ga/, 1) # match because /a/ starts at 1
'xhay'match(/\Ga/, 1) # no match because character at 1 is 'h'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.