![](/img/trans.png)
[英]How do I detect the presence of a substring in 1 string in another string?
[英]How do I detect the presence of this line?
這個問題與我在這里剛剛問過的一個問題有關,因此請原諒我,如果其中大部分語言看起來相似。
我有一個包含多行的字符串。 我正在做的是檢查每一行的特定特征,然后對它們進行相應的處理。
+
或-
開頭。 那很好。 \\n
,並且Ilya幫助我弄清楚如何檢測這些行,那很好。 -
或+
開頭的行之后。 脫離上下文,這是我要查找的有效字符串的示例: " end\\n",
但是,這是在以+
或-
開頭的行之后的上下文中的一個更完整的示例。
"+ Reflection.add_reflection self, name, reflection\n",
" end\n",
" \n",
"- habtm_reflection = ActiveRecord::Reflection::HasAndBelongsToManyReflection.new(name, scope, options, self)\n",
在這種特殊情況下,我嘗試選擇第二行。
在這種情況下,與純字符串匹配參數匹配的字符串將被取消資格,因為它們出現在以-
或+
開頭的字符串之前。
" #\n",
" # All of the association macros can be specialized through options. This makes cases\n",
" # more complex than the simple and guessable ones possible.\n",
"- module ClassMethods\n",
我希望這很清楚。
編輯1
為了更清楚地說明我要尋找的內容。 基本上,我將字符串分成了幾行,然后在每一行上進行迭代。
這就是我所做的:
<% diff.body.lines.each do |dl| %>
<% if dl.start_with?("-") %>
<% elsif dl.start_with?("+") %>
<% elsif dl.strip.empty? %>
<% end %>
<% end %>
所以我想做的就是修改以上的if
語句集以適應最新的行檢查,或者找到某種方式通過添加另一個elsif
條件來檢查它。...盡管考慮到我需要知道發生了什么上面的一行我沒有看到如何修改而不修改if
語句。
str = [
"+ Reflection ...\n",
" end\n",
" \n",
"- habtm_reflection = ...\n"].join
str[/(^[+-].*$)\n(?!\n)(^[^+-].*$)/, 2]
#⇒ " end"
正則表達式基本上查找即開始與線要么+
OT -
用(^[+-].*$)
跳過\\n
,然后匹配未開始的一個行+
或-
與(^[^+-].*$)
。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.