Skip to main content
 首页 » 编程设计

C#正则表达式模式匹配

2024年02月20日47hnrainll

我们有一个字符串

string strScope = "This site is used for business group. [Title]Business Group[/Title][URL]http://google.com[\URL]"; 

在 C# 中,我们如何从上述字符串的标题和 url 中获取业务组。

请您参考如下方法:

测试正则表达式的重要资源是 Regexr .

\[Title\]([^\[]+)\[/Title\]\[URL\]([^\[]+)\[\\URL\] 

以上将与您发布的内容相匹配。我假设您打算在 URL 中使用“/”,这将由

匹配
\[Title\]([^\[]+)\[/Title\]\[URL\]([^\[]+)\[/URL\] 

代码示例(假设您实际上想要 [\URL]

        string strScope = "This site is used for business group. [Title]Business Group[/Title][URL]http://google.com[\URL]"; 
 
        var match = Regex.Match( strScope, @"\[Title\]([^\[]+)\[/Title\]\[URL\]([^\[]+)\[\\URL\]"); 
        if ( match.Groups.Count >= 2) 
        { 
            string name = match.Groups[0].Value; 
            string url = match.Groups[1].Value; 
        } 

如果您想要更传统的 [/URL],显然可以使用其他正则表达式