[英]Javascript regex to match between two patterns, where first pattern is optional
我嘗試了很多事情並嘗試調整類似的答案......但今天仍然失敗了,如果有人能幫助我,我將永遠感激!
我需要使用正則表達式(我使用的 JS 詞法庫不允許其他任何東西)來匹配:
$$
和*/
之間的任何內容$$
*/
鑒於這種:
xxx. 123 $$yyy.234 */zzz.567
^^^^^^^^^^
...我需要匹配指定的字符串。
因此,這似乎工作正常:
(?<=\$\$)(?:[\s\S])*?(?:[\s\S])*?\*\/
(...如這里所見)
但是還有一個額外的要求:
$$
, $$
匹配字符串的開頭。例如:
xxx. 123 yyy.234 */zzz.567
^^^^^^^^^^^^^^^^^^^
是的,在我的正則表達式知識的限制下,無法登陸! :-(
可能值得一提的是,開頭的$$
符號並不是那么可靠,它更像是:
\$[\p{L}0-9_]*?\$
當與www $$ xxx $$ yyy */ zzz
匹配時,我假設結果應該是$$ yyy */
而不是$$ xxx $$ yyy */
。 如果這不是必需的,那么解決方案可能比實際需要的更復雜。
(?: ^ | \$\$ ) # Starting at the start of the string or at "$$"
( (?: (?!\$\$). )* # A sequence of characters (.) now of which starting with "$$"
\*/ # Followed by "*/"
) # End capture
除了不完全。 這將失敗$$$abc*/
。 所以我們修復:
(?: ^ | \$\$(?!\$) ) # Starting at the start of the string or at "$$" (but not "$$$")
( (?: (?!\$\$). )* # A sequence of characters (.) now of which starting with "$$"
\*/ # Followed by "*/"
)
我們也可以避免前瞻。
(?: ^ | \$\$ )
( (?: [^$]+ ( \$[^$]+ )* \$? )?
\*/
)
關於更新的問題,可以修改前瞻版本以適應\\$[\\p{L}0-9_]*\\$
。
(?: ^
| \$ [\p{L}0-9_]* \$ (?! [\p{L}0-9_]* \$ )
)
( (?: (?! \$ [\p{L}0-9_]* \$ ) . )*
\*/
)
我使用換行符和空格來提高可讀性。 您將需要刪除它們(因為 JS 的引擎似乎沒有像其他引擎那樣導致它們被忽略的標志)。
我知道這已經得到了回答和接受。 但這是最短的方法。
let str = "xxx. $$ 123 $$yyy.234 */zzz.567";
let regex = /\$?\w*\$?([\w \d.-]*\$?[\w \d.-]*\*\/)/gm;
console.log(regex.exec(str)[1]);
更新:
如評論中所述,上述方法對於a $ b */
類型的字符串失敗。 所以,我想出了這個。 這不如@ikugami 的好,但這絕對可以是另一種方式。
let str = "$$xxx. $$gjjd*/ fhjgd";
let regex = /(\$?\w*\$?)([\w \d.-]*\$?[\w \d.-]*\*\/)/gm;
result = regex.exec(str).slice(1);
if (result[0].startsWith('$')) {
result = result[1]
} else {
result = result[0] + result[1]
}
console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.