-1

I learn to regexp and I wanna ask, can I save value for use in same regexp? Im trying to split html to tags.

like:

/<[a-zA-Z]*>.*<\/[a-zA-Z]*>/gi
  --------       --------
   val a          val b

and I need a == b, so is there any way how to save "val a" and use instead regexp named as "val b"?

Richard Hutta
  • 659
  • 7
  • 12
  • 7
    You're using the wrong tool for the job. [Don't use regex to parse HTML](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). – zzzzBov Jun 04 '13 at 17:41
  • 2
    You shouldn't be using regex to parse html tags: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – David Sherret Jun 04 '13 at 17:41
  • 2
    Check out [Grouping and Backreferences](http://www.regular-expressions.info/brackets.html) – Bergi Jun 04 '13 at 17:45

2 Answers2

2

First, the obligatory warning, you cannot parse HTML with regex.

That being said, you can use a capture group and refer to it within the regex using \#, where # is the number of the capture group (starting with 1). For example:

/<([a-zA-Z]*)>.*<\/\1>/gi

However again, you should not use this regex because it is broken. There are much better ways to handle HTML, especially in Javascript.

Community
  • 1
  • 1
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • 1
    I would not call that regexp "broken", it is perfectly valid and performs a possibly useful function. But, as we all agree, it does not come anywhere close to parsing HTML. – HBP Jun 04 '13 at 17:51
1

Use \1, \2, ... It will refer to matched groups

/(\d)x(\1)/.test("1x1") // true
/(\d)x(\1)/.test("1x2") // false
BrunoLM
  • 97,872
  • 84
  • 296
  • 452