scala - Negative lookbehind in a regex with an optional prefix -
scala - Negative lookbehind in a regex with an optional prefix -
we using next regex recognize urls (derived this gist jim gruber). beingness executed in scala using scala.util.matching in turn uses java.util.regex:
(?i)\b((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?!js)[a-z]{2,6}/)(?:[^\s()<>{}\[\]]+)(?:[^\s`!()\[\]{};:'".,<>?«»“”‘’])|(?:(?<!@)[a-z0-9]+(?:[.\-][a-z0-9]+)*[.](?!js)[a-z]{2,6}\b/?(?!@))) this version has escaped forwards slashes, rubular:
(?i)\b(((?:https?:(?:\/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?!js)[a-z]{2,6}\/)(?:[^\s()<>{}\[\]]+)(?:[^\s`!()\[\]{};:'".,<>?«»“”‘’])|(?:(?<!@)[a-z0-9]+(?:[.\-][a-z0-9]+)*[.](?!js)[a-z]{2,6}\b\/?(?!@)))) previously front-end sending plaintext end, they're allowing users create anchor tags urls. hence end needs recognize urls except in anchor tags. tried accomplish negative loohbehind, ignoring urls href=" prefix
(?i)\b((?<!href=")((?:https?: ... etc the problem our url regex liberal, recognizing http://www.google.com, www.google.com, , google.com - given
<a href="http://www.google.com">google</a> the negative lookbehind ignore http://www.google.com, regex still recognize www.google.com. i'm wondering if there's succinct way tell regex "ignore www.google.com , google.com if substrings of ignored http(s)://www.google.com"
at nowadays i'm using filter on url regex matches (code in scala) - ignores urls in link text (<a href="http://www.google.com">www.google.com</a>) ignoring urls > prefix , </a> suffix. i'd rather stick filter if doing in regex create complicated regex more unreadable.
urlpattern.findallmatchin(text).tolist.filter(m => { val start: int = m.start(1) val end: int = m.end(1) val ishref: boolean = (start - 6 > 0) && text.substring(start - 6, start) == """href="""" val isanchor: boolean = (start - 1 > 0 && end + 3 < text.length && text.substring(start - 1, start) == ">" && text.substring(end, end + 3) == "</a>") !(ishref || isanchor) && option(m.group(1)).isdefined }) <a href=\s+|\b((?:https?:(?:\/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?!js)[a-z]{2,6}\/)(?:[^\s()<>{}\[\]]+)(?:[^\s`!()\[\]{};:'".,<>?«»“”‘’])|(?:(?<!@)[a-z0-9]+(?:[.\-][a-z0-9]+)*[.](?!js)[a-z]{2,6}\b\/?(?!@)))
or
<a href=(?:(?!<\/a>).)*<\/a>|\b((?:https?:(?:\/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?!js)[a-z]{2,6}\/)(?:[^\s()<>{}\[\]]+)(?:[^\s`!()\[\]{};:'".,<>?«»“”‘’])|(?:(?<!@)[a-z0-9]+(?:[.\-][a-z0-9]+)*[.](?!js)[a-z]{2,6}\b\/?(?!@))) try this. is:
consumes href links cannot matched later
does not capture not appear in groups anyways.
process rest before.
see demo.
http://regex101.com/r/vr4fy4/17
regex scala regex-lookarounds
Comments
Post a Comment