Recursive regular expression,how to match the coupled string with regular expression?
... AA BB sysodufsoufdds BB AA ...
Where AA
,BB
can be arbitary consecutive string with no space in it.
But I want to get the outest pair:AA
More examples:
Input:
a HH CC abc CC HH c
Output:
HH
Input:
x YYYY j DD GG DD hsu DD GG DD k YYYY o
Output:
YYYY
To make my question more general,how to match a specific tag in html with regular expression?I've seen various posts discussing about this,but none of them give a answer by regex.Related questions are: I'm looking 开发者_StackOverflowfor a regular expression to remove a given (x)HTML tag from a string
\b(\w{2,})\b.*\b\1\b
will match everything from the first series of consecutive characters until its repetition. Backreference \1
will contain the pattern that was matched (e. g. AA, HH or YYYY in your examples).
The \b
s are necessary to enforce word boundaries.
EDIT: Oh. I just noticed that you want to do something else entirely, namely remove HTML tags from a string/file. Don't use regexes for that. I won't quote the article that everyone else always quotes when someone asks a question like this, but the problem (in a nutshell) is that HTML is not regular, and trying to use regexes here is just asking for trouble. That's the reason why nobody (in their right mind) uses regular expressions to "parse" HTML - they use a parser.
That said, I have used regexes to extract data from well-formed XML sources where I knew the structure exactly and knew that the tags I'm interested in would never be nested etc. - but recursion with regular expressions is just horribly complicated if it works at all (C# and Perl have some support for that, but it's incredibly hairy).
I think you need back references here. Something like (trying to avoid specifics of any regex language):
(\w+) \w* (\w+) \w+ \1 \w* \2
With the first capture being you result.
I've assumed single spaces separating the strings to keep it clearer, you probably need to allow for arbitrary whitespace with \s+
, and \w
(identifier characters: roughly [a-zA-Z9-0_]
) is the right match for the strings.
精彩评论