正则表达式操作从字符串中查找自定义标记内的字符串

时间:2013-11-28 08:44:04

标签: c# regex

嗨,我有一个像这样的字符串

    "[fconsender]Username (11:00 AM):[/fconsender] Hi Good Afternoon!"

    "[fconreceiver]AnotherUser (11:02 AM):[/fconreceiver] Yea! How are you ?"

我想在[fconsender]和[/ fconsender]中提取字符串 [fconreceiver]和[/ fconreceiver] ...... 我怎样才能使用正则表达式来实现它.... 它只是为了分隔用户和聊天字符串......

2 个答案:

答案 0 :(得分:1)

尝试使用此模式:

<强>模式

(?<=\[fconsender\])(.+?)(?=\[\/fconsender\])|(?<=\[fconreceiver\])(.+?)(?=\[\/fconreceiver\])

C#代码

string regex = @"(?<=\[fconsender\])(.+?)(?=\[\/fconsender\])|(?<=\[fconreceiver\])(.+?)(?=\[\/fconreceiver\])";

string myString = "[fconreceiver]AnotherUser (11:02 AM):[/fconreceiver] Yea! How are you ?" +
                  "[fconsender]Username (11:00 AM):[/fconsender] Hi Good Afternoon!";

MatchCollection matches = Regex.Matches(myString, regex);

foreach(Match m in matches)
{
    Console.WriteLine(m);
}

Console.ReadLine();

<强> INPUT

  

[fconsender]用户名(上午11:00):[/ fconsender]嗨下午好!

     

[fconreceiver] AnotherUser(上午11:02):[/ fconreceiver]是的!你好吗?

<强>输出

Username (11:00 AM):
AnotherUser (11:02 AM):

修改

请求OP的chatstring模式:

<强>模式

(?<=\[\/fconsender\] )(.+?)(?=\n|$|\[)|(?<=\[\/fconreceiver\] )(.+?)(?=\n|$|\[)

<强> INPUT

  

[fconsender]用户名(上午11:00):[/ fconsender]嗨下午好!

     

[fconreceiver] AnotherUser(上午11:02):[/ fconreceiver]是的!你好吗?

<强>输出

Hi Good Afternoon!
Yea! How are you ?

答案 1 :(得分:0)

只需使用[[a-zA-Z0-9 \ s] +](?。*)[/ [a-zA-Z0-9 \ s] +]并提取内容组匹配以检索匹配< / p>