Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.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 如何获取正则表达式中出现的字符的索引?_Ruby_Regex_Ruby On Rails 5 - Fatal编程技术网

Ruby 如何获取正则表达式中出现的字符的索引?

Ruby 如何获取正则表达式中出现的字符的索引?,ruby,regex,ruby-on-rails-5,Ruby,Regex,Ruby On Rails 5,在Ruby中(使用Ror5.0.1),我希望得到文本块中数字“2”的索引 "\n2 hel2 lo" 但是,我只想要两个的索引,如果它前面有空格或行的开头,后面有空格。所以我做了一个小小的regex 2.4.0 :007 > regex = /([[:space:]]|^)2([[:space:]]|\.|\))/ => /([[:space:]]|^)2([[:space:]]|\.|\))/ 2.4.0 :008 > text_content = "\n2 hel2 l

在Ruby中(使用Ror5.0.1),我希望得到文本块中数字“2”的索引

"\n2 hel2 lo"
但是,我只想要两个的索引,如果它前面有空格或行的开头,后面有空格。所以我做了一个小小的regex

2.4.0 :007 > regex = /([[:space:]]|^)2([[:space:]]|\.|\))/
 => /([[:space:]]|^)2([[:space:]]|\.|\))/
2.4.0 :008 > text_content = "\n2 hel2 lo"
 => "\n2 hel2 lo"
2.4.0 :009 > text_content.index(regex)
 => 0

但是很明显,这个正则表达式返回零,因为这是正则表达式第一次出现的地方。我想要一个返回“1”的表达式,因为1是正则表达式中“2”所在位置的索引。如何做到这一点?

您的正则表达式在字符串开头正确匹配,但您只需要获取从
2
开始的模式的位置,因此,我建议将
([[:space:]|^)
部分转换为
(?反向查找:

regex = /(?<![^[:space:]])2([[:space:].)])/
text_content = "\n2 hel2 lo"
text_content.index(regex)  
# => 1
regex=/(?1

(?lookbehind(在当前位置的左侧匹配一个位置,该位置前面没有非空白)是一个零宽度断言,将只检查是否存在,并且文本不会是匹配的一部分,因此,您将获得正确的位置。

您可以使用
/(?“\n2 hel2 lo.”索引(/(?1)
>“2 hel2 lo”。索引(/(?0
>“abc 2 hel2 lo”,索引(/(?4
>“abc hel2 lo”,索引(/(?无)
请注意,它在字符串末尾不匹配:

> "abchel2 lo 2".index(/(?<=\s|^)2\s/)
=> nil
>“abchel2低2”。索引(/(?零
(?!\S)
是一种负向前瞻,它规定
“2”
后面不能跟非空白字符

如果字符串可能包含多个满足条件的
“2”
,并且所有匹配都需要索引,则可以使用刚才给定的相同正则表达式(
r=/(?)。(我假设a
“2”
如果字符串前面有空格字符,或者字符串开头也有空格字符,则字符串结尾处为匹配项。)

arr=[]
“\n2 302 2 2”。扫描(r){arr[1,7,9]
见,1和


1
Regexp.last\u match
返回全局变量的值
$~

好吧,试试
text\u content.index(/(?@sagarpandya82,如果我想匹配行的开头或数字之前的空格怎么办?我试过了/(?@Wiktor,应该先试一下你的建议--/(?为什么不
/(?@dawg:,和末尾的
\s
不匹配
(而OP模式匹配)。
> "abchel2 lo 2".index(/(?<=\s|^)2\s/)
=> nil
r = /
    (?<!\S)  # do not match a non-whitespace character (negative lookbehind)
    2        # match 2
    (?=\s)   # match a whitespace character in a positive lookahead
    /x       # free-spacing regex definition mode

"\n2 hel2 lo" =~ r  #=> 1
"42 hel 2 lo" =~ r  #=> 7
"42 hel*2 lo" =~ r  #=> nil
r = /(?<!\S)2(?!\S)/
"2" =~ r  #=> 0`
arr = []
"\n2 302 2 2".scan(r) { arr << Regexp.last_match.begin(0) }
arr
  # => [1, 7, 9]