如何在c#中使用正则表达式提取两个特殊字符之间的字符串

本文关键字:两个 特殊字符 字符串 之间 提取 正则表达式 | 更新日期: 2023-09-27 18:09:11

我对正则表达式完全陌生。我需要实现的是,我有一个字符串变量包含以下字符串例如,

"My Name is #P_NAME# and I am #P_AGE# years old"

我需要使用正则表达式提取两个字符串P_NAME和P_AGE(到字符串数组或两个字符串变量等)。例如,字符串以#开始,以#结束,我需要提取中间部分。

如何在c#中使用正则表达式做到这一点?

如果我在中间有一个新的行字符,我如何提取上面相同的内容呢?例如,

"My Name is #P_NAME# and 'r'n I am #P_AGE# years old".

感谢

谢谢大家…

以下内容对我有效…我不能发布我自己的答案作为答案,直到8小时在stackoverflow过期…:)

string str = "My Name is #P_NAME# and 'r'n I am #P_AGE# years old";
MatchCollection allMatchResults = null;
var regexObj = new Regex(@"#'w*#");
allMatchResults = regexObj.Matches(str);

'allMatchResults'包含#P_NAME#和#P_AGE#(即包括#字符)。但是有它比没有它对我的其他逻辑有帮助。

如何在c#中使用正则表达式提取两个特殊字符之间的字符串

你可以这样做

using System.Text.RegularExpressions;
using System;
public class Test
{
        public static void Main(){
                string s = "My name is #Dave# and I am #18# years old";
                Regex r = new Regex(@"#(.+?)#");
                MatchCollection mc = r.Matches(s);
                Console.WriteLine("Name is " + mc[0].Groups[1].Value);
                Console.WriteLine("Age is " + mc[1].Groups[1].Value);
        }
}

演示

我不知道你的应用程序是什么,但我必须说这不是一个非常健壮的数据传输方法。如果有多余的#,就会出问题。比如名字里有#的人!

但是,如果你能保证你总是使用这种格式的字符串,那么这是可行的。

Regex #(.+?)#说明

第一个#匹配#

(开始。在代码中索引到.Groups[1][0]是完全匹配的,例如#Dave#而不仅仅是Dave

.+?至少匹配一个字符。.是一个字符。+是重复(至少)一次)。?告诉regex引擎是懒惰的-所以不要匹配#,因为它将被我们最终的#匹配

) close group

#匹配另一个# -在本例中是'关闭'的那个

"#[^#]+#"这样的正则表达式将匹配一个散列,后面跟着一个或多个非散列字符,后面跟着另一个散列。

有多种替代方法可以解决这个问题,例如"#.*?#"

以下代码将输出#P_NAME#和#P_AGE#。

string p = "My Name is #P_NAME# and 'r'n I am #P_AGE# years old";
Regex reg = new Regex("#[^#]+#");
MatchCollection matches = reg.Matches(p);
foreach (Match m in matches)
{
    Console.WriteLine(m.Value);
}

这是一个基于此的扩展方法…享受。:)

BTW -这不会保留#字符-这是我不想要的-你可以将RegEx更改为上面的那些字符来获得。

public static class StringExtensions
{
    ///----------------------------------------------------------------------
    /// <summary>
    /// Gets the matches between delimiters.
    /// </summary>
    /// <param name="source">The source string.</param>
    /// <param name="beginDelim">The beginning string delimiter.</param>
    /// <param name="endDelim">The end string delimiter.</param>
    /// <returns></returns>
    /// <example>
    /// string beginDelim = "<span>";
    /// string endDelim = "</span>";
    /// string input = string.Format("My Name is {0}Lance{1} and I am {0}39{1} years old", beginDelim, endDelim);
    ///
    /// var values = input.GetMatches(beginDelim, endDelim);
    /// foreach (string value in values)
    /// {
    ///     Console.WriteLine(value);
    /// }
    /// </example>
    ///----------------------------------------------------------------------
    public static IEnumerable<string> GetMatches(this string source, string beginDelim, string endDelim)
    {
        Regex reg = new Regex(string.Format("(?<={0})(.+?)(?={1})", Regex.Escape(beginDelim), Regex.Escape(endDelim)));
        MatchCollection matches = reg.Matches(source);
        return (from Match m in matches select m.Value).ToList();
    }
}

Try -

var results = new List<string>();
var subjectString = "My Name is #P_NAME# and 'r'n I am #P_AGE# years old";
Regex regexObj = new Regex("#.+?#");
Match matchResults = regexObj.Match(subjectString);
while (matchResults.Success) {
    results.Add(matchResults.ToString().Replace("#",""));
    matchResults = matchResults.NextMatch();
}

将结果写入results数组。

谢谢大家。

以下方法对我有效…

string str = "My Name is #P_NAME# and 'r'n I am #P_AGE# years old";
MatchCollection allMatchResults = null;
var regexObj = new Regex(@"#'w*#");
allMatchResults = regexObj.Matches(str);

'allMatchResults'包含#P_NAME#和#P_AGE#(即包括#字符)。但它对我的其他逻辑有帮助

没有人提到多行情况,所以如果你有多行字符串,比如:

var testcase = @"Here is my info
#
John Doe
18 years old
#";
var regex = new Regex(@"#(.+?)#", RegexOptions.Singleline);
var match = regex.Match(testcase);
match.Groups[1].Value.Dump();
// OR
var matches = regex.Matches(testcase);
foreach (Match m in matches) m.Groups[1].Value.Dump();
/*
Output:
John Doe
18 years old
*/

您需要指定SingleLine标志来忽略换行符并转义正斜杠。

为将来读者提供的答案

尝试使用

var format = "My Name is #P_NAME# and 'r'n I am #P_AGE# years old";
Regex rgxp = new Regex(@"#[(?<name>'S+)']#", RegexOptions.Compiled);
Match m = rgxp .Match(format);
if (true == m.Success)
{
   return m.Groups["name"].Value;     // <-- this statement returns the value you're looking for
}