当前位置: 首页>>代码示例>>C#>>正文


C# Regex.Split方法代码示例

本文整理汇总了C#中System.Text.RegularExpressions.Regex.Split方法的典型用法代码示例。如果您正苦于以下问题:C# Regex.Split方法的具体用法?C# Regex.Split怎么用?C# Regex.Split使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Text.RegularExpressions.Regex的用法示例。


在下文中一共展示了Regex.Split方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: TwoSPInstance

        public TwoSPInstance(string file)
        {
            Regex regex = new Regex(@"\s+");

            using (StreamReader reader = File.OpenText(file)) {
                string line = "";

                // Getting the dimension.
                line = reader.ReadLine();
                while (line.Trim() == "") {
                    line = reader.ReadLine();
                }
                NumberItems = int.Parse(regex.Split(line.Trim())[0]);

                // Getting the width of the strip.
                line = reader.ReadLine();
                while (line.Trim() == "") {
                    line = reader.ReadLine();
                }
                StripWidth = int.Parse(regex.Split(line.Trim())[0]);

                // Getting height and width of each item.
                ItemsHeight = new int[NumberItems];
                ItemsWidth = new int[NumberItems];
                for (int i = 0; i < NumberItems; i++) {
                    line = reader.ReadLine();
                    while (line.Trim() == "") {
                        line = reader.ReadLine();
                    }
                    string[] parts = regex.Split(line.Trim());
                    ItemsHeight[i] = int.Parse(parts[0]);
                    ItemsWidth[i] = int.Parse(parts[1]);
                }
            }
        }
开发者ID:HondaDai,项目名称:metaheuristics,代码行数:35,代码来源:TwoSPInstance.cs

示例2: GerarLogradouro

        public Logradouro GerarLogradouro(string cepDesejado, string tipoCEP = "ALL", string semelhante = "N")
        {
            var postData = string.Format("relaxation={0}&tipoCEP={1}&semelhante={2}", cepDesejado, tipoCEP, semelhante);
            
            var responseString = GetHtml(postData, _buscarLogradouroPeloCepLink);

            var pattern = @"<table class=""tmptabela"">(.*?)</table>";
            var regex = new Regex(pattern);
            var match = regex.Match(responseString);

            var rua = new Regex("<td width=\"150\">(.*?)&nbsp;</td>").Match(match.Groups[0].Value).Groups[0].Value;
            string stripTagsPattern = @"<(.|\n)*?>";
            rua = Regex.Replace(rua, stripTagsPattern, string.Empty).Replace("&nbsp;","");

            var bairro = new Regex("<td width=\"90\">(.*?)&nbsp;</td>").Match(match.Groups[0].Value).Groups[0].Value;
            bairro = Regex.Replace(bairro, stripTagsPattern, string.Empty).Replace("&nbsp;", "");

            var cidade = new Regex("<td width=\"80\">(.*?)</td>").Match(match.Groups[0].Value).Groups[0].Value;
            cidade = Regex.Replace(cidade, stripTagsPattern, string.Empty).Replace("&nbsp;", "");

            var logradouro = new Logradouro();
            logradouro.CEP = cepDesejado;
            logradouro.Endereco = rua.HtmlDecode();
            logradouro.BairroOuDistrito = bairro.HtmlDecode();
            logradouro.Localidade = cidade.Split('/')[0].HtmlDecode();
            logradouro.UF = cidade.Split('/')[1].HtmlDecode();
            return logradouro;
        }
开发者ID:CadnunsDev,项目名称:ConsultaCepCorreios,代码行数:28,代码来源:BuscadorCepCorreiosHelper.cs

示例3: Diff

        public Collection<MultiLineDiff> Diff(string originalStr, string newStr)
        {
            Regex reg = new Regex(@"\r\n");
            string[] originalLines = reg.Split(originalStr);
            string[] newLines = reg.Split(newStr);

            Collection<MultiLineDiff> trances = new Collection<MultiLineDiff>();

            int[][] tracesMatrix = new int[originalLines.Length + 1][];
            //Init matrix
            for (int i = 0; i < originalLines.Length + 1; i++)
            {
                tracesMatrix[i] = new int[newLines.Length + 1];
                for (int j = 0; j < newLines.Length + 1; j++)
                {
                    tracesMatrix[i][j] = -1;
                }
            }

            int minEditLength = MinEditLength(originalLines, newLines, 0, 0, tracesMatrix);
            trances = GetTraces(originalLines, newLines, tracesMatrix);

            string html = GenerateDiffHTML(trances, originalLines, newLines);

            return trances;
        }
开发者ID:daizhen,项目名称:JsonCompare,代码行数:26,代码来源:LineDiff.cs

示例4: buttonBrowse_Click

        /// <summary>
        /// Browse button even handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            fd.Filter = "VCG files|*.vcg|All Files|*.*";
            if (fd.ShowDialog() == DialogResult.OK)
            {
                textBoxInputFilePath.Text = fd.FileName;
                selectedFilePath = fd.FileName;

                if (selectedFilePath != "")
                {
                    myLogicLayer.identifyLoops(selectedFilePath);
                    richTextBoxBasicBlock.Text = "";
                    richTextBoxBackEdgesInCfg.Text = "";
                    richTextBoxLoopInformation.Text = myLogicLayer.getLoops();

                    Regex r = new Regex("\\n");
                    String[] lines = r.Split(myLogicLayer.getIntermidiateCodeAsBasicBlocks());
                    //Next, I take each line and process its contents like so.
                    foreach (string l in lines)
                    {
                        ParseLine(l);
                    }

                    lines = r.Split(myLogicLayer.getBackEdges());
                    //Next, I take each line and process its contents like so.
                    foreach (string l in lines)
                    {
                        parseBackEdges(l);
                    }
                }

            }
        }
开发者ID:jajdoo,项目名称:pascal_pp_ide,代码行数:39,代码来源:LoopIdentificationForm.cs

示例5: Main

        static void Main()
        {
            long currentIIndex = 0;
            const string SplitPattern = @"\s+";
            Regex splitter = new Regex(SplitPattern);

            string[] inputStringNumbers = splitter.Split(Console.ReadLine()).Where(s => s != string.Empty).ToArray();
            BigInteger[] numberArray = inputStringNumbers.Select(BigInteger.Parse).ToArray();
            long arrayLength = numberArray.Length;

            while (true)
            {
                string command = Console.ReadLine();

                if (command == "stop")
                {
                    break;
                }

                string[] commandArgs = splitter.Split(command).Where(s => s != string.Empty).ToArray();

                long operationIndex = CalculateOperationIndex(commandArgs, currentIIndex, arrayLength);

                ExecuteCommand(commandArgs, numberArray, operationIndex);

                currentIIndex = operationIndex;

            }

            string output = string.Format("[{0}]", string.Join(", ", numberArray));
            Console.WriteLine(output);
        }
开发者ID:KatyaMarincheva,项目名称:CSharp-Advanced,代码行数:32,代码来源:ArraySlider.cs

示例6: CreateDiffHtml

        public string CreateDiffHtml(string originalStr, string newStr)
        {
            Regex reg = new Regex(@"\r\n");
            string[] originalLines = reg.Split(originalStr);
            string[] newLines = reg.Split(newStr);

            Collection<MultiLineDiff> trances = Diff(originalStr, newStr);

            string html = GenerateDiffHTML(trances, originalLines, newLines);

            return html;
        }
开发者ID:daizhen,项目名称:JsonCompare,代码行数:12,代码来源:LineDiff.cs

示例7: IGRequestChangeProperty

 public IGRequestChangeProperty(string sUser, string sFrameId, string sPropIds, string sPropVals)
     : base(sUser, IGREQUESTFRAMECHANGEPROPERTY_STRING, IGREQUEST_FRAME_CHANGEPROPERTY, sFrameId)
 {
     SetParameter(IGREQUEST_ISFRAME, sFrameId == "0" ? "0" : "1");
     SetParameter(IGREQUEST_PROPIDS, sPropIds);
     Regex RE = new Regex(@"[,]+");
     string[] tPropIds = RE.Split(sPropIds);
     string[] tPropVals = RE.Split(sPropVals);
     if (tPropIds.Count() == tPropVals.Count())
     {
         for (int idxPropId = 0; idxPropId < tPropIds.Count(); idxPropId++)
             SetParameter(tPropIds[idxPropId], tPropVals[idxPropId]);
     }
 }
开发者ID:JBetser,项目名称:Imagenius_SDK,代码行数:14,代码来源:IGRequestFrame.cs

示例8: GetLiquidCodeOfParameter

		private string GetLiquidCodeOfParameter(string name)
		{
			var retVal = string.Empty;

			Regex regex = new Regex(
				@"(?<=[A-Z])(?=[A-Z][a-z])|(?<=[^A-Z])(?=[A-Z])|(?<=[A-Za-z])(?=[^A-Za-z])"
			);

			if(regex.Split(name).Length > 0)
			{
				retVal = "{{ context." + string.Join("_", regex.Split(name)).ToLower() + " }}";
			}

			return retVal;
		}
开发者ID:tuyndv,项目名称:vc-community,代码行数:15,代码来源:LiquidNotificationTemplateResolver.cs

示例9: GetTorrents

 public static string[][] GetTorrents(string address, string username, string password)
 {
     WebClient wc = new WebClient();
     wc.Credentials = new NetworkCredential(username, password);
     string fullAddress = "http://" + address + "/gui/?list=1";
     //Fetch a raw listing of the current stuff from uTorrent==============================================
     byte[] rawResponse = wc.DownloadData(fullAddress);
     string response = Encoding.ASCII.GetString(rawResponse);
     Regex arrayBuilder = new Regex("\n");
     char[] delimiters = new char[] { '"', '[', ']' };
     int start = response.IndexOf('"' + "torrents" + '"' + ": [") + 16;
     int end = response.Length - (start + 29);
     response = response.Substring(start, end);
     //Clean the list text so its just the torrents=======================================================
     string[] rawTorrents = arrayBuilder.Split(response);
     string[][] torrents = new string[rawTorrents.Count()][];
     if (rawTorrents.Count() > 0)                //check for active torrents
     {
         for (int i = 0; i < rawTorrents.Count(); ++i)
         {
             string rawTorrent = rawTorrents[i];
             string[] tempTorrent = rawTorrent.Split(new Char[] { ',' });
             //now we fill the array torrents with: 0 = Hash, 1 = Status, 2 = Label, and 3 = Queue
             torrents[i] = new string[] { tempTorrent[0].ToString().Trim(delimiters), tempTorrent[1].ToString().Trim(delimiters), tempTorrent[11].ToString().Trim(delimiters), tempTorrent[17].ToString().Trim(delimiters), tempTorrent[2].ToString().Trim(delimiters) };
         }
     }
     return torrents;
 }
开发者ID:Jkinney,项目名称:Unseen-Hand,代码行数:28,代码来源:uTorrentTalker.cs

示例10: PhotoUploadedInfo

        public PhotoUploadedInfo(string jsonstr)
        {
            // отрезаем скобки, убираем кавычки
            System.Windows.Forms.MessageBox.Show(jsonstr);
            jsonstr = jsonstr.Replace("{", "").Replace("}", "").Replace("\"", "");

            // разделяем строку на кусочки по  запятой с пробелами
            Regex r = new Regex(@"\,[\s]*");
            string[] json = r.Split(jsonstr);

            // далее каждый кусок обрабатываем как ключ: значение
            // и складываем их в таблицу
            Hashtable h = new Hashtable();
            r = new Regex(@"(\:[\s]+)");
            foreach (string str in json)
            {
                string[] kv = r.Split(str);
                h[kv[0]] = kv[2];
            }

            // присваиваем значения
            this.Server = (string)h["server"];
            this.Photo = (string)h["photo"];
            this.Hash = (string)h["hash"];
        }
开发者ID:kholodovitch,项目名称:vk_winamp,代码行数:25,代码来源:PhotoUploadedInfo.cs

示例11: RegExpTest_1_Split_Test_0

        public MFTestResults RegExpTest_1_Split_Test_0()
        {
            bool testResult = false;

            string[] expectedResults;

            string[] acutalResults;

            Regex regex;

            try
            {
                expectedResults = new string[]{ "xyzzy", "yyz", "123" };
                regex = new Regex("[ab]+");
                acutalResults = regex.Split("xyzzyababbayyzabbbab123");
                TestTestsHelper.AssertEquals(ref expectedResults, ref acutalResults, out testResult);

                expectedResults = new string[] { "xxxx", "xxxx", "yyyy", "zzz" };
                regex = new Regex("a*b");//match any amount of 'a' and 1 'b'
                acutalResults = regex.Split("xxxxaabxxxxbyyyyaaabzzz");
                TestTestsHelper.AssertEquals(ref expectedResults, ref acutalResults, out testResult);                

                // Grep Tests

                return RegExpTest_2_Grep_Test_0(ref acutalResults);

            }
            catch (Exception ex)
            {
                Log.Exception("Unexpected Exception", ex);
                testResult = false;
            }

            return (testResult ? MFTestResults.Pass : MFTestResults.Fail);
        }
开发者ID:koson,项目名称:.NETMF_for_LPC17xx,代码行数:35,代码来源:Split_Grep_Tests.cs

示例12: FromString

        public void FromString(string listString)
        {
            // remove existing list items
            Clear();

            if ( listString != null )
            {
                // remove leading and trailing whitespace
                // NOTE: Need to check if .NET whitespace = SVG (XML) whitespace
                listString = listString.Trim();

                if ( listString.Length > 0 )
                {
                    Regex delim = new Regex(@"\s+,?\s*|,\s*");
                    foreach ( string item in delim.Split(listString) )
                    {
                        // the following test is needed to catch consecutive commas
                        // for example, "one,two,,three"
                        if ( item.Length == 0 )
                            throw new DomException(DomExceptionType.SyntaxErr);

                        AppendItem(new SvgNumber(item));
                    }
                }
            }
        }
开发者ID:codebutler,项目名称:savagesvg,代码行数:26,代码来源:SvgNumberList.cs

示例13: Partition

        public string[] Partition(string input)
        {
            Regex r=new Regex("([ \\t{}():;])");

            Normalize_Casing(ref input);
            //normalization to the lower case
            input=input.ToLower() ;

            String [] tokens=r.Split(input);

            ArrayList filter=new ArrayList() ;

            for (int i=0; i < tokens.Length ; i++)
            {
                MatchCollection mc=r.Matches(tokens[i]);
                if (mc.Count <= 0 && tokens[i].Trim().Length > 0 )
                    filter.Add(tokens[i]) ;

            }

            tokens=new string[filter.Count] ;
            for(int i=0; i < filter.Count ; i++) tokens[i]=(string) filter[i];

            return tokens;
        }
开发者ID:acinmavi,项目名称:english-practice-helper,代码行数:25,代码来源:Tokeniser.cs

示例14: SplitHelper

		public string [] SplitHelper( string macroName, string splitOrRegex, bool usingRegex )
		{
			// ******
			//NmpStringList list = null;
			string [] list = null;

			if( usingRegex ) {
				try {
					Regex rx = new Regex( splitOrRegex );
					//list = new NmpStringList( rx.Split(theString, MaxParseItems) );
					list = rx.Split(theString, MaxParseItems );
				}
				catch ( ArgumentException e ) {
					ThreadContext.MacroError( "{0}: {1}", macroName, e.Message );
				}
			}
			else {
				try {
					//list = new NmpStringList( rx.Split(theString, MaxParseItems) );
					list = theString.Split(new string [] { splitOrRegex }, MaxParseItems, StringSplitOptions.None );
				}
				catch ( ArgumentException e ) {
					ThreadContext.MacroError( "{0}: {1}", macroName, e.Message );
				}
			}

			// ******
			return list;
		}
开发者ID:jmclain,项目名称:Nmp,代码行数:29,代码来源:StringObjectHelper.cs

示例15: TokenizeMessage

        public static List<object> TokenizeMessage(string message)
        {
            var tokens = new List<object>();

            try
            {
                //TODO - better Regex
                var r = new Regex("<(.|\n)*?>", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.ExplicitCapture);
                var split = r.Split(message);

                foreach (var t in split)
                {
                    if (!string.IsNullOrWhiteSpace(t))
                    {
                        Uri uri = null;
                        if (Uri.TryCreate(t, UriKind.Absolute, out uri))
                        {
                            tokens.Add(uri);
                        }
                        else
                        {
                            tokens.Add(t);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                tokens.Clear();
                tokens.Add(message);
            }

            return tokens;
        }
开发者ID:JustinBeckwith,项目名称:JabbRPhone,代码行数:34,代码来源:MessageHelper.cs


注:本文中的System.Text.RegularExpressions.Regex.Split方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。