What is the correct way to write a Regular Expression to find a paragraph?
// Expressão Regular
var minhaExpressao = /<p>.*</p>/;
How can I fix this variable?
What is the correct way to write a Regular Expression to find a paragraph?
// Expressão Regular
var minhaExpressao = /<p>.*</p>/;
How can I fix this variable?
You can use RegExp /^<p>.+<\/p>$/gm
, where:
^<p>
will ensure that the start of the line is <p>
.+
takes all elements after the initial tag, you can change it to better understand this part, for only characters, only numbers, in this case it is for any character <\/p>$
to ensure that the end is </p>
remembering to escape the bar You can use this expression to get the paragraph if it also has line breaks:
<p>[\w\W]+<\/p>
Example:
var p1 = document.querySelector("#div1").textContent;
var p2 = document.querySelector("#div2").textContent;
var re = /<p>[\w\W]+<\/p>/;
var para1 = p1.match(re)[0];
var para2 = p2.match(re)[0];
console.log(para1);
console.log(para2);
<textarea id="div1">
<p>
Isto é um parágrafo onde as tags não estão na mesma linha do texto
</p>
</textarea>
<textarea id="div2">
<p>Isto é um parágrafo onde as tags estão na mesma linha do texto</p>
</textarea>
\w\W -> captura letra e o que não é letra (ou seja, tudo)
+ -> quantificador que une as ocorrências
See RegExr
The only thing that is incorrect in your regex is </p>
, the bar should be escaped, thus: /<p>.*<\/p>/
;
I noticed that no one used a regex called rearview , that is, you get the reference of a particular group in the order in which it was defined in the expression.
The regex below will catch any type of tag, generalizing a little, but if you want to specify paragraphs just change where has (.*>)
and (p>)
, this regex will be able to get the opening tag until the tag closing, including the content between tags.
<(.*>).*<\/
let texto = '<p>Este é uma paragrafo</p>
<b>Este é um texto em negrito</b>
<b>Fechamento Incorreto, não deve dar match<b>'
const expressao = /<(.*>).*<\//gm
console.log(texto.match(expressao));