英文:
C# Regex to split using space but exclude text between [: and :] special characters
问题
- 需要正则表达式来拆分文本,但排除**[:和:]**特殊字符之间的文本。
one
[two two]
three
[:four four:]
five
six
[seven seven:]
[:eight eight]
- 需要正则表达式来拆分文本,但排除**[:和:]特殊字符之间的文本以及[和]**特殊字符之间的文本。
one
[two two]
three
[:four four:]
five
six
[seven seven:]
[:eight eight]
英文:
I need two C# Regular expressions to split using space but exclude text between [: and :] special characters.
- Need regex to split text but exclude text between [: and :] special characters.
- Need regex to split text but exclude text between [: and :] and also the text between [ and ] special characters.
Example: 1st Case:
string input1 = "one [two two] three [:four four:] five six [seven seven:] [:eight eight]";
output:
one
[two
two]
three
[:four four:]
five
six
[seven
seven:]
[:eight
eight]
Example: 2nd Case:
output:
one
[two two]
three
[:four four:]
five
six
[seven
seven:]
[:eight
eight]
I tried this but not working, producing below output
string input1 = "one [two two] three [:four four:] five six [seven seven:] [:eight eight]";
var parts1 = Regex.Matches(input1, @"[[::]].+?[\[::]]|[^ ]+").Cast<Match>()
.Select(m => m.Value)
.ToArray();
one
[two two] three [:four four:]
five
six
[seven seven:]
[:eight
eight]
答案1
得分: 1
var pattern = @"\[:[^][]*:]|\[(?!:)[^][]*(?<!:)]|\S+";
var results = Regex.Matches(text, pattern).Cast<Match>().Select(x => x.Value);
详情:
\[:
-[:
字符串[^][]*
- 零个或多个非[
和]
的字符:]
|
- 或\[
- 一个[
字符(?!:)
- 紧接在右侧,不能是:
字符[^][]*
- 零个或多个非[
和]
的字符(?<!:)]
- 一个]
字符,前面不能有:
|
- 或\S+
- 一个或多个非空白字符。
<details>
<summary>英文:</summary>
You can use
```c#
var pattern = @"\[:[^][]*:]|\[(?!:)[^][]*(?<!:)]|\S+";
var results = Regex.Matches(text, pattern).Cast<Match>().Select(x => x.Value);
See the regex demo.
Details:
\[:
-[:
string[^][]*
- zero or more chars other than[
and]
:]
|
- or\[
- a[
char(?!:)
- immediately on the right, there should be no:
[^][]*
- zero or more chars other than[
and]
(?<!:)]
- a]
char that has no:
right before it|
- or\S+
- one or more non-whitespace chars.
答案2
得分: 0
I think your input case might be wrong, it should be string input1 = "one [two two] three [:four four:] five six [:seven seven:] [:eight eight:]";
And you can use this regex to have the desired array:
var parts1 = Regex.Replace(input1, @"\[\:[a-z ]+\:\] *|\[[a-z ]+\] ", "").Trim().Split(' ');
英文:
I think your input case might be wrong, it should be string input1 = "one [two two] three [:four four:] five six [:seven seven:] [:eight eight:]";
And you can use this regex to have the desired array:
var parts1 = Regex.Replace(input1, @"\[\:[a-z ]+\:\] *|\[[a-z ]+\] *", "").Trim().Split(' ');
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论