检测特定标记的字符串。 C#字符串、标记

2023-09-03 15:58:06 作者:孤单的像条狗

我有一个非常大的字符串(HTML),并在此HTML存在这样的情况他们都以#和#

I have a very large string (HTML) and in this HTML there is particular tokens where all of them starts with "#" and ends with "#"

简单的如

<html>
<body>
      <p>Hi #Name#, You should come and see this #PLACE# - From #SenderName#</p>
</body>
</html>

我需要一个code,能够检测到这些标记,并把它放在一个列表。 0 - #姓名# 1 - #将# 2 - #SenderName#

I need a code that will detect these tokens and will put it in a list. 0 - #Name# 1 - #Place# 2 - #SenderName#

我知道,我可以使用正则表达式也许,反正你有一些想法,这样做呢?

I know that I can use Regex maybe, anyway have you got some ideas to do that?

推荐答案

是的,你可以使用普通的EX pressions。

Yes you can use regular expressions.

string test = "Hi #Name#, You should come and see this #PLACE# - From #SenderName#";
Regex reg = new Regex(@"#\w+#");
foreach (Match match in reg.Matches(test))
{
    Console.WriteLine(match.Value);
}

正如你可能已经猜到了\ W表示任何字母数字字符。的+表示,它可能会出现1次或多次。你可以在这里找到更多的信息 MSDN文档(用于.NET 4.你会发现其他版本那里也)。

As you might have guessed \w denotes any alphanumeric character. The + denotes that it may appear 1 or more times. You can find more info here msdn doc (for .Net 4. You'll find other versions there as well).