我在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)
答案 0 :(得分:1)
这是一个正则表达式模式,可以匹配代码块。如果字符串中未包含{},则会失败。
(.*?){(?:[^{}]+|{(?<n>)|}(?<-n>))+(?(n)(?!))*}
这是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