微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

提供给字符串数组列表的Breaking Format和String

如何解决提供给字符串数组列表的Breaking Format和String

我有一个格式(数据类型-字符串),格式为{1}.{0}.{2}@xyz.com。另外,我有一个遵循相同格式的字符串,称为bht.aay.ccch@xyz.com。如何将字符串分解为列表,字符串数组或任何其他数据结构提供的格式(格式中提供的Number是应存储相应字符串的索引)。分隔符可以是或/

示例:-

1) Format - {0}.{1}@xyz.com  
   String - name0.name1@xyz.com  
   String array[]= { "name0","name1"}
2) Format - {1}.{0}.{2}@xyz.com  
   String - pos0.pos1.pos2@xyz.com  
   String array[]= { "pos1","pos0","pos2"}
3) Format - {0}.{1}  
   String - name0.name1  
   String array[] = { "pos0","pos1"}

解决方法

using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConAppCore
{
    class Program
    {
        static void Main(string[] args)
        {
            Test("{0}.{1}@xyz.com","name0.name1@xyz.com");
            Test("{1}.{0}.{2}@xyz.com","pos0.pos1.pos2@xyz.com");
            Test("{0}.{1}","name0.name1");
        }
        static void Test(string format,string input)
        {
            string pattern = CreatePattern(format);
            var match = Regex.Match(input,pattern);

            var array = match.Groups
                .OfType<Group>()
                .Skip(1)
                .OrderBy(g => g.Name,StringComparer.Ordinal)
                .Select(g => g.Value)
                .ToArray();

            Console.WriteLine(string.Join(",",array));
        }
        static string CreatePattern(string format)
        {
            var sb = new StringBuilder();
            var match = Regex.Match(format,@"(.*?)\{(\d+)\}");
            int index;
            int length;

            do
            {
                sb.Append(Regex.Escape(match.Groups[1].Value));
                sb.Append("(?'group").Append(match.Groups[2].Value).Append(@"'\w+)");

                index = match.Index;
                length = match.Length;

                match = match.NextMatch();

            } while (match.Success);

            sb.Append(Regex.Escape(format.Substring(index + length)));

            return sb.ToString();
        }
    }
}
,

尝试以下操作:

df <- structure(list(Name = c("John Smith","John Smith","Jane Doe","Lisa Brown"),Grade = c("C","B","C","A","B")),class = "data.frame",row.names = c(NA,-6L))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。