Ruby Regexp#match匹配字符串的开头与给定位置(Python重新匹配)

时间:2012-11-19 11:19:29

标签: ruby regex

我正在寻找一种方法来匹配第一个符号的字符串,但考虑到我给匹配方法的偏移量。

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">

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如何使用字符串切片?

/^qwe/.match(test_string[def_pos..-1])

pos参数告诉正则表达式引擎在哪里开始匹配,但它不会改变行首(和其他)锚点的行为。 ^仍然只在一行的开头匹配(qwe_pos仍在test_string的中间。)

此外,在Ruby中,\A是“字符串开始”锚点,\z是“字符串结束”锚点。 ^$也匹配行的开头/结尾,并且没有选项可以更改该行为(这对Ruby来说是特殊的,就像使用(?m)的迷人混淆一样(?s)在其他正则表达式中的作用)...

相关问题