regex c# optional group - should act greedy?

此生再无相见时 提交于 2019-12-24 02:48:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!