如何在C#中使用正则表达式提取两个特殊字符之间的字符串 [英] How to extract the strings between two special characters using Regular Expressions in C#

查看:993
本文介绍了如何在C#中使用正则表达式提取两个特殊字符之间的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我的名字是#P_NAME#,我已经#P_AGE#岁



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



如何在C#中使用正则表达式来做到这一点。 / p>

如果我之间也有换行符,该如何提取上面的内容。例如,



我的名字是#P_NAME#,\r\n我今年#P_AGE#岁。



谢谢



谢谢大家...



以下为我工作...在8个小时后stackoverflow中,我无法发布自己的答案作为答案...:)

  string str =我的名字是#P_NAME#,并且\r\n我今年#P_AGE#岁; 

MatchCollection allMatchResults = null;
var regexObj = new Regex(@#\w *#);
allMatchResults = regexObj.Matches(str);

allMatchResults包含#P_NAME#和#P_AGE#(即,包含#个字符)。但是拥有它比不拥有它有助于我的其他逻辑。

解决方案

谢谢大家。



以下为我工作。 。

  string str =我的名字是#P_NAME#,\r In我今年#P_AGE#岁 ; 

MatchCollection allMatchResults = null;
var regexObj = new Regex(@#\w *#);
allMatchResults = regexObj.Matches(str);

allMatchResults包含#P_NAME#和#P_AGE#(即,包含#个字符)。但是拥有它有助于我的其他逻辑


I am totally new to regular expressions. And what I need to achieve is, I have a string variable containing the following string for example,

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

I need to extract the two strings P_NAME and P_AGE using regular expressions (to a string array or two string variables etc). i.e. the string starts with a # and ends with a # and I need to extract the middle part.

How can I do this in C# using Regular Expressions..?

And how can I extract the same above in case I have a new line character in between as well. i.e. for example,

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

Thanks

Thanks Everyone...

Following worked for me... I cannot publish my own answer as the answer until 8 hours expires in 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' contains #P_NAME# and #P_AGE# (i.e. including # character). But having it helps my other logics than not having it.

解决方案

Thanks everyone..

Following worked for me...

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' contains #P_NAME# and #P_AGE# (i.e. including # character). But having it helps my other logic

这篇关于如何在C#中使用正则表达式提取两个特殊字符之间的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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