找到字符串中标记相对于另一个的位置

时间:2012-03-08 12:04:15

标签: ruby algorithm text substring

我有两个字符串,一个是清理过的,一个是MARKER。这个MARKER是一个固定的字符串,任意选择,由其他一些代码插入到字符串中。

 sanitized = "100 biz other stuff"
 marked = " 100    biz MARKER other stuff"

现在将MARKER的周围环境与sanitized进行匹配 字符串。

 # _ is empty, the string is expanded for visual only
 sanitized =  "100 ___biz_______ other stuff"
 marked =    " 100    biz MARKER other stuff"

获取MARKER字符串中sanitized的索引。

 sanitized =  "100 ___biz_MARKER other stuff"
                          ^
 marked =    " 100    biz MARKER other stuff"

哪个是7

2 个答案:

答案 0 :(得分:0)

我不清楚你要问的是什么。听起来你只需要知道如何在字符串中找到字符串的位置。

virtual = "100 biz MARKER other stuff"
virtual.index 'MARKER'
# => 8

答案 1 :(得分:0)

你的问题很模糊,但这可能会有所帮助:

s = "100 biz other stuff"
m = s.match(/(100 biz )(other stuff)/)
m.offset(1)
=> [0, 8]
m.offset(2)
=> [8, 19]
s.insert(m.offset(1)[1], "MARKER ")
=> "100 biz MARKER other stuff"