简体   繁体   English

REGEX模式处理或不处理引号

[英]REGEX Pattern to deal with or without quotes

I have the following BBCode that I needed to parse 我有以下需要解析的BBCode

[url=http://www.google.com]Google[/url]
[url="http://www.google.com"]Google[/url]

What I am trying to do is extract both http://www.google.com and Google 我要做的是提取http://www.google.comGoogle

Now the difference between the two pieces of BBCode above is the quotes around the url in the second BBCode. 现在,上面两个BBCode之间的差异是第二个BBCode中的url周围的引号。

Is it possible for a single regex code to extract my datapoints and account for the presence or abscense of quotes? 单个正则表达式代码是否有可能提取我的数据点并解释引号的存在或不存在?

Thanks! 谢谢!

EDIT : Just for further clarification. 编辑 :只是为了进一步澄清。 I am currently using the following Regex pattern: 我目前正在使用以下正则表达式模式:

/\[URL=\"?([\s\S]*?)\"?\]([\s\S]*?)\[\/URL\]/gi

This will successfully match the URL if it is wrapped in quotes or not. 如果URL用引号括起来,这将成功匹配URL。 However, I would like the final result to be stripped of all quotes. 但是,我希望最终结果能够被删除所有引号。 Is this possible via the actual regex pattern itself to simply not include the quotes in the match (if the quotes are even there) 这是否可以通过实际的正则表达式模式本身来简单地不包括匹配中的引号(如果引号甚至在那里)

Yes: 是:

/\[url=("?)(http://www\.google\.com)\1\](Google)\[\/url\]/

will capture '"' or '' ; 'http://www.google.com' ; and 'Google' . 将捕获'"''' ; 'http://www.google.com' ;以及'Google'

(I realize you don't actually need to capture the '"' or '' , but that's how the regex manages to require that the double-quotes either both be present or both be absent. I also realize that you probably need to cover other link-targets and link-texts besides your example, but I'm assuming that you already know how to handle that, and are just asking about the issue with the optional double-quotes?) (我意识到你实际上并不需要捕获'"''' ,但这就是正则表达式设法要求双引号要么都存在要么两者都不存在。我也意识到你可能需要覆盖除了你的例子之外的其他链接目标和链接文本,但我假设你已经知道如何处理它,并且只是询问可选双引号的问题?)

To make it more general you would do something like this: 为了使它更通用,你会做这样的事情:

/\[url=\"?(https?://[^"\]]+)"?\]([^\[]+)\[\/url\]/

which will give you the URL in \\1 and the label in \\2 它将为您提供\\ 1中的URL和\\ 2中的标签

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM