[英]Limit regex expression by character in c#
我得到以下模式(\\s\\w+)
我需要用空格将字符串中的每个单词匹配。
例如
当我有这个字符串
many word in the textarea must be happy
我懂了
many
word
in
the
textarea
must
be
happy
是正确的,但是例如当我有另一个角色时
many word in the textarea , must be happy
我懂了
many
word
in
the
textarea
must
be
happy
但是must be happy
应该被忽略,因为我希望它在字符串中出现另一个字符时中断
编辑:
例子2
all cats { in } the world are nice
应该退货
all
cats
因为{
是我的另一个分隔符
例子3
My 3 cats are ... funny
应该退货
My
3
cats
are
因为3
是字母数字和.
是我的分隔符
我能做什么?
为此,您需要使用\\G
定位符来匹配字符串开头或最后匹配之后的位置。 因此您可以使用以下模式进行操作:
@"(?<=\G\s*)\w+"
[^\w\s\n].*$|(\w+\s+)
尝试this.Grab的捕获或matches.See demo.Set标志m
为多行模式。
参见演示。
我认为我是Sam的评论是正确的:您将需要两个正则表达式。
这是相应的代码:
"^(\\\\w+\\\\s+)+"
"(\\\\w+\\\\s+)"
您可以将两者结合起来,很容易地捕获单个单词-就像这样
"^(\\\\w+\\\\s+)+"
这是演示该模式的完整代码:
string input = "many word in the textarea , must be happy";
string pattern = "^(\\w+\\s+)+";
Match match = Regex.Match(input , pattern);
// Never returns a NullReferenceException because of GroupsCollection array indexer - check it out!
foreach(Capture capture in match.Groups[1].Captures)
{
Console.WriteLine(capture.Value);
}
编辑
查看Casimir et Hippolyte,这是一个非常干净的答案。
合计一个正则表达式:-)结果在list
Regex regex = new Regex(@"^((\w+)\s*)+([^\w\s]|$).*");
Match m = regex.Match(inputString);
if(m.Success)
{
List<string> list =
m.Groups[2].Captures.Cast<Capture>().
Select(c=>c.Value).ToList();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.