首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Ruby将字符串的开头与给定的位置进行匹配(类似Regexp#match )

Ruby将字符串的开头与给定的位置进行匹配(类似Regexp#match )
EN

Stack Overflow用户
提问于 2012-11-19 19:19:29
回答 1查看 185关注 0票数 2

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

代码语言:javascript
运行
复制
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

我要找的是:

代码语言:javascript
运行
复制
/...qwe/.match(test_string, def_pos) # => nil
/...qwe/.match(test_string, qwe_pos) # => #<MatchData "qwe">

有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-19 19:26:24

使用字符串片怎么样?

代码语言:javascript
运行
复制
/^qwe/.match(test_string[def_pos..-1])

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

此外,在Ruby语言中,\A是“字符串开头”锚点,\z是“字符串结尾”锚点。^$也匹配行的开头/结尾,并且没有选项来改变这种行为(这是Ruby所特有的,就像(?m)在其他正则表达式中所做的那样,它做的是(?s)所做的那样)……

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13452699

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档