如何在第 n 次出现的正则表达式结束的字符串中找到索引?
How do I find the index in a string of where my nth occurrence of a regex ends?
使用 Rails 5.0.1 和 Ruby 2.4。如何在第 n 次出现的正则表达式结束的字符串中找到索引?如果我的正则表达式是
/\-/
我的字符串在哪里
str = "a -b -c"
我正在寻找我的正则表达式第二次出现的最后一个索引,我希望答案是 5。我试过这个
str.scan(StringHelper::MULTI_WHITE_SPACE_REGEX)[n].offset(1)
但出现错误
NoMethodError: undefined method `offset' for " ":String
在上面,n 是一个整数,表示我要扫描的正则表达式的第 n 次出现。
一种方法:
def index_of_char str, char, n
res = str.chars.zip(0..str.size).select { |a,b| a == char }
res[n]&.last
end
index_of_char "a -b -c", '-', 0
#=> 2
index_of_char "a -b -c", '-', 1
#=> 5
index_of_char "a -b -c", '-', 2
#=> nil
index_of_char "abc", '-', 1
#=> nil
可以进一步优化。
抱歉之前的快速阅读。也许这个方法可以帮助你找到一个元素第n次出现的索引。尽管我在 ruby 中找不到使用严格正则表达式执行此操作的方法。希望这有帮助。
def index_of_nth_occorunce(string, element, nth_occurunce)
count = 0
string.split("").each_with_index do |elm, index|
count += 1 if elm == element
return index if count == nth_occurunce
end
end
index_of_nth_occorunce("a -b -c", "-", 2) #5
在进一步挖掘之后,我可能已经在这个堆栈中找到了您正在寻找的答案 post (ruby regex: match and get position(s) of)。希望这也能有所帮助。
nth_occurence = 2
s = "a -b -c"
positions = s.enum_for(:scan, /-/).map { Regexp.last_match.begin(0) }
p positions[nth_occurence - 1] # 5
根据我从 link 发展到 related question 的评论:
那个问题的答案
"abc12def34ghijklmno567pqrs".to_enum(:scan, /\d+/).map { Regexp.last_match }
可以很容易地进行调整以获取单个项目的 MatchData
string.to_enum(:scan, regex).map { Regexp.last_match }[n - 1].offset(0)
在字符串中查找第 n
个匹配项。
使用 Rails 5.0.1 和 Ruby 2.4。如何在第 n 次出现的正则表达式结束的字符串中找到索引?如果我的正则表达式是
/\-/
我的字符串在哪里
str = "a -b -c"
我正在寻找我的正则表达式第二次出现的最后一个索引,我希望答案是 5。我试过这个
str.scan(StringHelper::MULTI_WHITE_SPACE_REGEX)[n].offset(1)
但出现错误
NoMethodError: undefined method `offset' for " ":String
在上面,n 是一个整数,表示我要扫描的正则表达式的第 n 次出现。
一种方法:
def index_of_char str, char, n
res = str.chars.zip(0..str.size).select { |a,b| a == char }
res[n]&.last
end
index_of_char "a -b -c", '-', 0
#=> 2
index_of_char "a -b -c", '-', 1
#=> 5
index_of_char "a -b -c", '-', 2
#=> nil
index_of_char "abc", '-', 1
#=> nil
可以进一步优化。
抱歉之前的快速阅读。也许这个方法可以帮助你找到一个元素第n次出现的索引。尽管我在 ruby 中找不到使用严格正则表达式执行此操作的方法。希望这有帮助。
def index_of_nth_occorunce(string, element, nth_occurunce)
count = 0
string.split("").each_with_index do |elm, index|
count += 1 if elm == element
return index if count == nth_occurunce
end
end
index_of_nth_occorunce("a -b -c", "-", 2) #5
在进一步挖掘之后,我可能已经在这个堆栈中找到了您正在寻找的答案 post (ruby regex: match and get position(s) of)。希望这也能有所帮助。
nth_occurence = 2
s = "a -b -c"
positions = s.enum_for(:scan, /-/).map { Regexp.last_match.begin(0) }
p positions[nth_occurence - 1] # 5
根据我从 link 发展到 related question 的评论:
那个问题的答案
"abc12def34ghijklmno567pqrs".to_enum(:scan, /\d+/).map { Regexp.last_match }
可以很容易地进行调整以获取单个项目的 MatchData
string.to_enum(:scan, regex).map { Regexp.last_match }[n - 1].offset(0)
在字符串中查找第 n
个匹配项。