[英]Match a string between two other strings with regex in javascript
[英]Regex expression to match string between two other strings
JavaScript中的另一個硬正則表達式:
我有這個字符串:
<td style="padding:0 2%">{% for product in products.pos01 %}
<table class="box-item" item-editable="" style="float:left;padding-bottom:10px; width:32%;border-spacing: 0px; border: 0px; border-collapse: collapse;"><tr><td style=" padding:10px 5px; vertical-align:top ">
<a href="**|product.url|**" class="button view-deal" style="padding:8px 10px; background-color: #fc5d26; text-decoration:none; display:inline-block; text-align:center; color:#fff; font-size:12px;margin:0px; line-height:140%;text-transform:uppercase">view deal</a></div></td></tr></table>{% if (loop.index0-2) is divisibleby 3 %}</td></tr><tr>
<td style="padding:0 2%">{% endif %}{% endfor %}
</td>
我正在嘗試從字符串{%for ...%}和{%endfor%}的任何循環中獲取內容
我已經嘗試過,但是無法
/({%for(!?%})+%})((!? endfor)*){%endfor%} / gm
但是沒用
我認為您應該使用與此類似的模式
正則表達式
(?<={% for[^%]*%})((?:.|\n)*)(?={% endfor %})
說明
(?<={% for[^%]*%})
:使用后向搜索模式{% for[^%]*%}
(?={% endfor %})
:使用超前搜索文本{% endfor %}
((?:.|\\n)*)
:for循環之間的一條消息,由變量$1
捕獲
但是如果您的語言不支持環視,則只需使用
正則表達式
({% for[^%]*%})((?:.|\n)*)({% endfor %})
說明
({% for[^%]*%})
:捕獲模式{% for[^%]*%}
到變量$1
({% endfor %})
:捕獲模式{% endfor %}
到變量$3
((?:.|\\n)*)
:for循環之間的一條消息,由$2
捕獲
只需根據您所用語言的限制修改我的regex
,即可完成此操作。
編輯
在搜索時,我認為Javascript
不支持環視,並且{
}
需通過\\
進行轉義。 我已經使用一些在線正則表達式測試儀對Java進行了正則表達式測試,我明白了。
(\{% for[^%]*%\})((?:.|\n)*)(\{% endfor %\})
要獲得所需的文本,只需使用變量$2
。
額外
如果您想捕獲嵌套循環內的消息,例如
消息示例
{% for product in products.pos01 %}
...
{% for product in products.pos02 %}
"messages"
{% endfor %}
...
{% endfor %}
要在此嵌套循環中捕獲"messages"
您只需將我以前的正則表達式修改為
(\{% for[^%]*%\}(?:.|\n)*\{% for[^%]*%\})((?:.|\n)*)(\{% endfor %\}(?:.|\n)*\{% endfor %\})
說明
(\\{% for[^%]*%\\}(?:.|\\n)*\\{% for[^%]*%\\})
:表示“ for循環的開始”,后跟“包括換行符在內的任何字符”和“開始for循環”
((?:.|\\n)*)
:我們的目標消息
(\\{% endfor %\\}(?:.|\\n)*\\{% endfor %\\})
:表示“ for循環結束”,后跟“包括換行符的任何字符”,后跟“ for循環結束”
注意,我只是重新排列了我以前的正則表達式來完成這項稍微復雜的工作。
試試這個正則表達式:
{% for [^\\0]+?{% endfor %}
說明:
{% for # search for text `{% for `
[^\0]+? # while not input's end
{% endfor %} # search for the next `{% endfor %}`
或者,如果您要分組:
{% (for [^\0]+?)%}([^\0]+?){% endfor %}
希望能幫助到你。
如果您嘗試獲取{% for ... %}
和{% endfor %}
則可能會起作用:
/%}([\W\w]*){%/gm
說明 :
%} matches the characters %} literally
\W match any non-word character [^a-zA-Z0-9_]
\w match any word character [a-zA-Z0-9_]
{% matches the characters {% literally
g modifier: global. All matches (don't return on first match)
m modifier: multi-line.
范例 :
https://regex101.com/r/pM3oX7/1
尚不清楚您是否要在%} {%
內獲取文本,還是要包含該部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.