当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Regex help pls for extracting values with quotes

问题描述:

I've been trying to create a RegEx for a string for almost a day and still haven't made it work, can anyone help?

string example (double quotes are options, and can also be single quotes):

"234"? "<img src=\"http://abc.com/a.jpg\" onclick=\"alert(\"\"working with 'quotes'?\"\");\" />"

and the following groups should be extracted:

234

<img src="http://abc.com/a.jpg" onclick="alert(""working with 'quotes'?"");" />

hope this is clear, anyone help pls!!

网友答案:

I'm not sure about the efficiency of this regex, but here is one that matched your string.

Rules

  1. Quotes around number are optional, and can be single-quotes.
  2. Quotes around html are optional, and can be single-quotes.
  3. Space(s) after question mark can be 0 or many.

Input

"234"? "<img src=\"http://abc.com/a.jpg\" onclick=\"alert(\"\"working with 'quotes'?\"\");\" />"

Regex

^['"]?(?<number>\d+)['"]?\?\s*['"]?(?<html>\<.*\>)['"]?$

Output Groups

number: 234
html: <img src=\"http://abc.com/a.jpg\" onclick=\"alert(\"\"working with 'quotes'?\"\");\" />
网友答案:

This is a quick solution (in JavaScript):

var s = "\"234\"? \"<img src=\"http://abc.com/a.jpg\" onclick=\"alert(\"\"working with 'quotes'?\"\");\" />\"";
var matches = s.match(/['"][\d]*['"](?=[\s]*\?)|['"]<[^><]*>['"]/ig);

The first part ['"][\d]*['"](?=[\s]*\?) matches numbers inside quotes followed by optional spaces and ?.
The second part ['"]<[^><]*>['"] matches any symbols (except <, >) inside quotes and <>.

One drawback of this solution is that matched results are wrapped in quotes.
Hope it helps you implement what you need.

分享给朋友:
您可能感兴趣的文章:
随机阅读: