简体   繁体   English

使用正则表达式分割字符串:* category ** bob *!cookshop

[英]Splitting a string using regex: *category**bob*!cookshop

This is what I have been trying so far. 到目前为止,这是我一直在尝试的方法。 Basically, I want to split the string but keep the separator. 基本上,我想分割字符串但保留分隔符。 My regex knowledge is very limited but I've been trying using a forward lookup to match the expression. 我的正则表达式知识非常有限,但是我一直在尝试使用正向查找来匹配表达式。 Whenever I try to introduce \\*1 into the string split, it goes badly so I'm not sure what to do and if this is possible. 每当我尝试在字符串拆分中引入\\*1 ,它都会变得很糟糕,因此我不确定该怎么办以及是否可行。

var tests = new List<string> 
{
    "*foo**bar*!bob",
    "*foo*!42",
    "!foo*bar*"
};

foreach (var expression in tests)
{
    var strings = Regex.Split(expression, @"(?=[!])");
    Console.WriteLine(String.Join(Environment.NewLine, strings));
}

1st line: 第一行:

*foo**bar*
!bob

2nd Line (this is working as expected) 第二行(按预期运行)

*foo*
!42

3rd line 第三行

{EMPTY LINE}
!foo*bar*

But I'm trying to get back is: 但我得到的回复是:

1st line 第一行

*foo*
*bar*
!bob

2nd line - As Above (this is correct) 第二行-如上(正确)

3rd line 第三行

!foo
*bar*

Try this... 尝试这个...

var tests = new List<string> 
{
    "*foo**bar*!bob",
    "*foo*!42",
    "!foo*bar*"
};

foreach (var expression in tests)
{
    var strings = Regex.Split(expression, @"(?=[!])|(\*[^\*]+\*)").Where(exp => !String.IsNullOrEmpty(exp));
    Console.WriteLine(String.Join(Environment.NewLine, strings));
}

Results: 结果:

*foo*
*bar*
!bob
*foo*
!42
!foo
*bar*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM