正则表达式在特定单词后捕获大括号

Regex to capture braces after specific word

我想在特定选择器之后捕获大括号之间的字符串。例如我有这样的字符串:

<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 它应该 return text-color:#211E22;bgcolor:test;

我可以在大括号之间获取数据,但不能使用特定的选择器。这是试过的代码 https://regex101.com/r/AESL8q/1

您可以对选择器和左大括号使用正向后视,然后捕获所有不是右大括号的字符,并对右大括号使用正向后视(可选):

/(?<=#123-module-container-eb7272147 p\{)[^}]+(?=\})/

  • (?<= ) 完成正后视。
  • 对于选择器,你必须转义一些字符,通常如果你有一个 class 选择器,点应该被转义。还有左大括号。
  • 大括号之间的匹配是 [^}]+ 说除右大括号外的任何字符一次或多次。在后面加一个问号会使它变得不受欢迎,但我认为没有必要。如果您使用点来匹配任何东西,就会出现这种情况。
  • 使用 (?= ) 完成正前瞻。

你可以在这里测试:

/**
 * 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">&lt;div id=&quot;text-module-container-eb7272147&quot; class=&quot;text-module-container&quot;&gt;&lt;style&gt;#123-module-container-eb7272147 p{text-color:#211E22;bgcolor:test;} #text-module-container-eb7272147 p{color:#211E1E;} #text-module-container-eb7272147 p{color:#123444;} &lt;/style&gt;&lt;div style=&quot;background-color: rgb(168, 27, 219); color: rgb(33, 30, 30);&quot;&gt;&lt;span style=&quot;color:#3498db;&quot;&gt;Click the edit button to replace this conte&lt;/span&gt;nt with your own.&lt;/div&gt;&lt;/div&gt;</textarea>
  </fieldset>
  <fieldset>
    <input type="submit" id="extract" value="Extract the CSS rules">
  </fieldset>
</form>

或在这里玩:https://regex101.com/r/N5cVKq/1