问题
having regex ~like this:
blablabla.+?(?:<a href="(http://.+?)" target="_blank">)?
I want to capture an url if I find one... finds stuff but I don't get the link (capture is always empty). Now if I remove the question mark at the end like this
blablabla.+?(?:<a href="(http://.+?)" target="_blank">)
This will only match stuff that has the link at the end... it's 2.40 am... and I've got no ideas...
--Edit--
sample input:
blablabla asd 1234t535 <a href="http://google.com" target="_blank">
expected output:
match 0:
group 1: <a href="http://google.com" target="_blank">
group 2: http://google.com`
I just want "http://google.com" or ""
回答1:
Are you doing a whole-string match? If so, try adding .*
to the end of the first regex and see what it matches. The problem with the first regex is that it can match anything after blablabla
because of the .+?
(leading to an empty capture), but the parenthesized part still won't match an a
tag unless it's at the end of the string. By the way, looking at your expected output, capture 1 will be the URL; the parentheses around the whole HTML tag are non-capturing because of the ?:
at the beginning.
回答2:
you shouldn't need .+? at the start, the regex is going to search the whole input anyway
you also have the closing '>' right after blank which will limit your matches
(?:<a href="(http://.+?)" target="_blank".*?>)
regex test
回答3:
It's the trailing ? that's doing you in. Reason: By marking it as optional, you're allowing the .+? to grab it.
blablabla.*(?:<a href="((http://)?.*)".+target="_blank".*>)
I modified it slightly... .+?
is basically the same as .*
, and if you may have nothing in your href (you indicated you wanted ""), you need to make the http optional as well as the trailing text. Also, .*
in front target
means you have at least one space or character, but may have more (multiple blanks or other attributes). .*
before the >
means you can have blanks or other attributes trailing after.
This will not match a line at all if there's no <a href...>
, but that's what you want, right?
The (?: ... )
can be dropped completely, if you don't need to capture the whole <a href...>
portion.
This will fail if the attributes are not listed in the order specified... which is one of the reasons regex can't really be used to parse html. But if you're certain the href will always come before the target, this should do what you need.
来源:https://stackoverflow.com/questions/5214940/regex-c-sharp-optional-group-should-act-greedy