Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby Regexp#匹配字符串开头与给定位置的匹配(类似Python)_Ruby_Regex - Fatal编程技术网

Ruby Regexp#匹配字符串开头与给定位置的匹配(类似Python)

Ruby Regexp#匹配字符串开头与给定位置的匹配(类似Python),ruby,regex,Ruby,Regex,我正在寻找一种从第一个符号匹配字符串的方法,但考虑到我给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) #

我正在寻找一种从第一个符号匹配字符串的方法,但考虑到我给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
test_string='abc def qwe'
def_位置=4
qwe_pos=8
/qwe/.match(测试字符串,定义位置)#=>#
#^^^这很糟糕,因为它只是跳过了“def”
/^qwe/.match(测试字符串,定义位置)#=>nil
#看起来不错。。。
/^qwe/.match(测试字符串,qwe位置)#=>nil
#^^^这很糟糕,因为它现在从来都不匹配“qwe”
我要找的是:

/...qwe/.match(test_string, def_pos) # => nil
/...qwe/.match(test_string, qwe_pos) # => #<MatchData "qwe">
/…qwe/.match(测试字符串,定义位置)=>nil
/…qwe/.match(测试字符串,qwe位置)=>#

有什么想法吗?

使用字符串片段怎么样

/^qwe/.match(test_string[def_pos..-1])
pos
参数告诉正则表达式引擎从何处开始匹配,但它不会更改行起始(和其他)锚的行为<代码> ^ 只在一行开始匹配(并且<代码> QWeiPoS仍然在TestOxSyth中)。


另外,在Ruby中,
\A
是“字符串的开始”锚点,
\z
是“字符串的结束”锚点
^
$
也匹配行的开头/结尾,并且没有任何选项可以更改该行为(这是Ruby特有的,就像
(?m)
的迷人的混乱用法一样,它与
(?s)
在其他正则表达式风格中的作用相同)

是的,谢谢。在类似的问题中得到了相同的想法:。现在只需要计算一下这对BIG stringsOkay的性能影响,它似乎并没有带来太大的性能冲击,我在评测中又赢得了1秒:)谢谢\a添加。在计算^(\n+)组在“<…”上匹配的原因时,新字符串对象将使用适当的新偏移量和长度元数据引用原始字符串的字符串存储区域。只读字符串切片的性能影响应该非常小。它设置了一个共享标志,以便在原始字符串或切片字符串发生后续变异时,可以遵循适当的写时复制语义。感谢您的评论。我不确定ruby字符串是否正确。