我正在寻找一种方法来匹配来自第一个符号的字符串,但考虑到我给match方法的偏移量。
test_string = 'abc def qwe'
def_pos = 4
qwe_pos = 8
/qwe/.match(test_string, def_pos) # => #<MatchData "qwe">
# ^^^ this is bad, as it just skipped over the 'def'
/^qwe/.match(test_string, def_pos) # => nil
# ^^^ looks ok...
/^qwe/.match(test_string, qwe_pos) # => nil
# ^^^ it's bad, as it never matches 'qwe' now我要找的是:
/...qwe/.match(test_string, def_pos) # => nil
/...qwe/.match(test_string, qwe_pos) # => #<MatchData "qwe">有什么想法吗?
发布于 2012-11-19 19:26:24
使用字符串片怎么样?
/^qwe/.match(test_string[def_pos..-1])pos参数告诉正则表达式引擎从哪里开始匹配,但它不会更改行首(和其他)锚点的行为。^仍然只在行首匹配(而qwe_pos仍然在test_string的中间)。
此外,在Ruby语言中,\A是“字符串开头”锚点,\z是“字符串结尾”锚点。^和$也匹配行的开头/结尾,并且没有选项来改变这种行为(这是Ruby所特有的,就像(?m)在其他正则表达式中所做的那样,它做的是(?s)所做的那样)……
https://stackoverflow.com/questions/13452699
复制相似问题