开发者

Problem finding exact regular expression pattern in C#

I am finding little tough figuring out the exact Regex for myself. I have a text where I have to search for a particular html like tag. The tag is like

<snippet lang="java">some java code</snippet>

My text is something like

This is a sample text where <snippet lang="java">some java code</snippet> and other sample text where this that <snippet lang="java">some java code 2</snippet>

can anyone suggest how can I write rege开发者_如何学Cx for this?


The most trivial one you can come up with would be:

<snippet lang="java">.*?</snippet>

You probably might want to capture whatever is contained between those tags in a group:

<snippet lang="java">(.*?)</snippet>

And maybe even make the java part variable:

<snippet lang="([^"]+)">(.*?)</snippet>

Quick PowerShell test:

PS> $text = 'This is a sample text where <snippet lang="java">some java code</snippet> and other sample text where this that <snippet lang="java">some java code 2</snippet>'

PS> [Regex]::Matches($text, '<snippet lang="([^"]+)">(.*?)</snippet>')


Groups   : {<snippet lang="java">some java code</snippet>, java, some java code}
Success  : True
Captures : {<snippet lang="java">some java code</snippet>}
Index    : 28
Length   : 45
Value    : <snippet lang="java">some java code</snippet>

Groups   : {<snippet lang="java">some java code 2</snippet>, java, some java code 2}
Success  : True
Captures : {<snippet lang="java">some java code 2</snippet>}
Index    : 112
Length   : 47
Value    : <snippet lang="java">some java code 2</snippet>

Mind you, this is all very basic Regex knowledge (or Regex 101 in US university (college?) parlance). If you need to ask such questions, maybe you should rethink whether you actually need regular expressions. As Jamie Zawinski once noted:

Some people, when confronted with a problem, think “I know, I'll use regular expressions.”
Now they have two problems.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜