如何精确选择字符串中的代码块(方法,函数)

时间:2018-10-16 16:31:06

标签: c# string

我在String中有一个代码,我只需要选择所需的方法即可,例如:

        "public void GetEntities(List<PublisherBO> _publishers, WebResourceBO _webResourceBO, SqlBO _sqlBO) {

            List<EntityBO> entities = new List<EntityBO>();

                List<EntityMetadata> results = entityDAO.GetAllEntities();
                EntitiesMetadata = results;
                entities = ConvertEntities(results);

            Data = entities;
        }

    public void ResetConnection() {
        sqlOpen = false;
        dynamicsOpen = false;

        if (Service != null) {

            if (Service.OrganizationWebProxyClient != null)
                Service.OrganizationWebProxyClient.Close();

            Service.Dispose();
        }
    }"

我只选择这个:

"public void ResetConnection() {
            sqlOpen = false;
            dynamicsOpen = false;

            if (Service != null) {

                if (Service.OrganizationWebProxyClient != null)
                    Service.OrganizationWebProxyClient.Close();

                Service.Dispose();
            }
        }"

我知道我必须使用IndexOf方法,复杂的是考虑{ },因为我知道我需要完成}中代码的选择,但是如何考虑其他{{1 }}放在此代码块中,并精确选择所有方法。

还有一个注意事项:我不能将其分成几行,因为某些代码只有1行(javascript)

1 个答案:

答案 0 :(得分:1)

这是一个正则表达式模式,可以匹配代码块。如果字符串中未包含{},则会失败。

(.*?){(?:[^{}]+|{(?<n>)|}(?<-n>))+(?(n)(?!))*}

Regex Storm

这是C#中的一个有效示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main (string[] args)
        {
            var text = @"public void GetEntities(List<PublisherBO> _publishers, WebResourceBO _webResourceBO, SqlBO _sqlBO) {

                                List<EntityBO> entities = new List<EntityBO>();

                                    List<EntityMetadata> results = entityDAO.GetAllEntities();
                                    EntitiesMetadata = results;
                                    entities = ConvertEntities(results);

                                Data = entities;
                            }

                        public void ResetConnection() {
                            sqlOpen = false;
                            dynamicsOpen = false;

                            if (Service != null) {

                                if (Service.OrganizationWebProxyClient != null)
                                    Service.OrganizationWebProxyClient.Close();

                                Service.Dispose();
                            }
                        }";
            var matches = Regex.Matches(text, "(.*?){(?:[^{}]+|{(?<n>)|}(?<-n>))+(?(n)(?!))*}");
            if (matches.Count > 0)
            {

            }
        }
    }
}

这里是正则表达式风暴的链接,显示了原始模式匹配的C#代码以及具有各种语法的JS代码 Regex Storm with C# and JS