如何在c#中编写参数化正则表达式 [英] how to write parameterized regular expression in c#

查看:140
本文介绍了如何在c#中编写参数化正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的,





我需要从字符串中搜索特定的文字。我的字符串包含以下文字

-------------------------

A 0 B 1 C 0

一:1



A 0 B 2 C 1

二:2



A 0 B 3 C 2

三:3

------------- ------------

我需要通过paramter来搜索精确的行,如果我通过参数(0,2,1)然后回答返回文本应该是2:2



我可以在这里使用正则表达式。



我也可以用foreach循环来做这个,但需要正常表达。



请建议。



问候,

YRishi

Dear All,


I need to searh specific text from string. My string contains below text
-------------------------
A 0 B 1 C 0
One: 1

A 0 B 2 C 1
Two: 2

A 0 B 3 C 2
Three: 3
-------------------------
I need to searh exact line by passing paramter like, if i pass paramater (0,2,1) then answer return text should Two:2

Can I use regular expression here.

I can also do this with foreach loop, but need to go with regular expression.

Please suggest.

Regards,
YRishi

推荐答案

你也可以不用循环..

如果它有用,你可以使用它。



You can do without looping also..
if it helpful, you can use this.

using System;
using System.Linq;

namespace oops1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "A 0 B 1 C 0" + "\n" +
                            "One: 1" + "\n" +
                           " A 0 B 2 C 1" + "\n" +
                            "Two: 2" + "\n" +
                            "A 0 B 3 C 2" + "\n" +
                            "Three: 3";

            string output = GetText(input, 0, 1, 0); //output is -> One: 1

            Console.WriteLine(output);
            Console.ReadLine();

        }

        public static string GetText(string input, int a, int b, int c)
        {
            string format = "A {0} B {1} C {2}";
            var array = input.Split('\n').ToList();
            int index = array.IndexOf(string.Format(format, a, b, c)) + 1;
            return array[index];
        }
    }
}


这篇关于如何在c#中编写参数化正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆