簡體   English   中英

這個正則表達式在 safari 上中斷,但在 Google Chrome 中有效,我如何讓它在兩者中都有效

[英]This regular expression breaks on safari but works in Google Chrome, how do I make it work in both

我有一個正則表達式:

var regex = /(layout)(^|\s*)((?<!=)=(?!=))(^|\s*)/;

這適用於 Google Chrome,但不適用於 Safari,也不適用於 Internet Explorer。 在 Safari 上,錯誤是:

"Invalid regular expression: invalid group specifier name"

請問我該如何解決這個問題?

更新我有一個 xml 輸入,我在將其提供給 xml 解析器之前對其進行了一些檢查。 其中一項檢查是我使用字符串解析來提取包含文件名的布局名稱。

我嘗試識別“布局”屬性上的空格並清理它,例如

<Container
width="match_parent"
height="wrap_content">

<include
width="20px"
height="30px"
layout  =   "subcontent.xml"
/>
</Container>

將更改為

<Container
width="match_parent"
height="wrap_content">

<include
width="20px"
height="30px"
layout="subcontent.xml"
/>

</Container>

我使用 String.replace 執行此操作,然后提取包含的文件名並從存儲中加載它並將其排隊以進行解析。

所以想:

let check = 'layout=';

//change layout[space....]=[space.....] to layout=
let regex = /(layout)(^|\s*)((?<!=)=(?!=))(^|\s*)/;
xml = xml.replace(regex, check);

我希望它現在更清楚。

利用

 let check = 'layout='; let xml = "change layout = "; let regex = /layout\s*=(?!=)\s*/g; xml = xml.replace(regex, check); console.log(xml)

請參閱正則表達式證明

解釋

"layout" - matches the characters layout literally (case sensitive)
"\s*" matches any whitespace character between zero and unlimited times, as many times as possible, giving back as needed (greedy)
"=" - matches the character = with index 6110 (3D16 or 758) literally
 - Negative Lookahead "(?!=)":
   Assert that the Regex below does not match
    "=" - matches the character = with index 6110 (3D16 or 758) literally
"\s*" - matches any whitespace character between zero and unlimited times, as many times as possible, giving back as needed (greedy)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM