我想在特定選擇器之后捕獲大括號之間的字串。例如我有這樣的字串:
<div id="text-module-container-eb7272147" class="text-module-container"><style>#123-module-container-eb7272147 p{text-color:#211E22;bgcolor:test;} #text-module-container-eb7272147 p{color:#211E1E;} #text-module-container-eb7272147 p{color:#123444;} </style>
現在如果我給選擇器#123-module-container-eb7272147 p它應該回傳text-color:#211E22;bgcolor:test;
我能夠在大括號之間獲取資料,但不能使用特定的選擇器。這是嘗試過的代碼https://regex101.com/r/AESL8q/1
uj5u.com熱心網友回復:
您可以在選擇器和左大括號中使用正向lookbehind,然后捕獲所有不是右大括號的字符,并為右大括號使用正向超前(可選):
/(?<=#123-module-container-eb7272147 p\{)[^}] (?=\})/
- 積極的向后看是用
(?<= ). - 對于選擇器,您必須轉義一些字符,通常如果您有一個類選擇器,則應該轉義點。開口大括號也。
- 你想要的大括號之間的匹配是
[^}]說除了右大括號之外的任何字符,一次或多次。在后面添加一個問號會使它變得不貪心,但我認為沒有必要。如果您使用點來匹配任何內容,就會出現這種情況。 - 積極的前瞻是用 完成的
(?= )。
你可以在這里測驗它:
/**
* Escape characters which have a meaning in a regular expression.
*
* @param string The string you need to escape.
* @returns The escaped string.
*/
function escapeRegExp(string) {
return string.replace(/[.* ?^${}()|[\]\\]/g, '\\$&');
}
let button = document.querySelector('#extract');
button.addEventListener('click', function(event) {
let html = document.querySelector('#html').value;
let selector = document.querySelector('#selector').value;
let pattern = new RegExp('(?<=' escapeRegExp(selector) '\s*\{)[^}] (?=\})');
let matches = pattern.exec(html);
if (matches) {
alert("The extracted CSS rules:\n\n" matches[0]);
}
event.preventDefault();
});
html, body {
font-family: Arial, sans serif;
font-size: 14px;
}
fieldset {
min-width: 30em;
padding: 0;
margin: 1em 0;
border: none;
display: flex;
}
label {
margin-right: 1em;
width: 6em;
}
input[type="text"],
textarea {
width: calc(100% - 7em);
min-width: 20em;
margin: 0;
padding: .25em .5em;
}
input[type="submit"] {
margin-left: 7.1em;
padding: .2em 1em;
}
<form action="#">
<fieldset>
<label for="selector">Selector: </label>
<input type="text" id="selector" name="selector"
value="#123-module-container-eb7272147 p">
</fieldset>
<fieldset>
<label for="">HTML code:</label>
<textarea id="html" name="html" cols="30" rows="10"><div id="text-module-container-eb7272147" class="text-module-container"><style>#123-module-container-eb7272147 p{text-color:#211E22;bgcolor:test;} #text-module-container-eb7272147 p{color:#211E1E;} #text-module-container-eb7272147 p{color:#123444;} </style><div style="background-color: rgb(168, 27, 219); color: rgb(33, 30, 30);"><span style="color:#3498db;">Click the edit button to replace this conte</span>nt with your own.</div></div></textarea>
</fieldset>
<fieldset>
<input type="submit" id="extract" value="Extract the CSS rules">
</fieldset>
</form>
或者在這里玩:https ://regex101.com/r/N5cVKq/1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/439698.html
標籤:javascript php jQuery 正则表达式 匹配
上一篇:嘗試動態更新資料時方法Collection::save不存在
下一篇:PHPCarbon不計算時差
