如何在花括号内将以下内容分成字符串数组?
我尝试过正则表达式,但是由于换了一行,所以该模式被放弃了
string script = @"{
ABC
DEF
}
{
GHI
LMN
}
{
QWE
ERT
}
"
返回完整的带有新行的数组
[“ ABC \ nDEF”,“ GHI \ nLMN”,“ QWE \ nERT”]
答案 0 :(得分:0)
嘿,我希望我做对了。 我知道这不是很好的解决方案,但这是什么。
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp6
{
internal class Program
{
private enum Token
{
Open,
Close,
Char,
UnKnowChar,
Space,
NewLine,
}
private static void Main(string[] args)
{
var text = @"{
ABC
DEF
}
{
GHI
LMN
}
{
QWE
ERT
}
";
var strings = Parse(text).ToArray();
}
private static IEnumerable<string> Parse(string text)
{
var strings = new List<string>();
var tokens = GetTokens(text);
var opens = tokens.Select((token, index) => new {token, index})
.Where(list => list.token == Token.Open).ToList();
foreach (var open in opens)
{
var index = tokens.FindIndex(open.index, token => token == Token.Close);
var substring = text.Substring(open.index + 1, index - open.index - 1);
var trim = substring.Trim('\r', '\n', ' ');
strings.Add(trim.Replace(' '.ToString(), string.Empty));
}
return strings;
}
private static List<Token> GetTokens(string text)
{
var tokens = new List<Token>();
foreach (var _char in text)
switch (_char)
{
case ' ':
tokens.Add(Token.Space);
break;
case '\r':
case '\n':
tokens.Add(Token.NewLine);
break;
case '{':
tokens.Add(Token.Open);
break;
case '}':
tokens.Add(Token.Close);
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
tokens.Add(Token.Char);
break;
default:
tokens.Add(Token.UnKnowChar);
break;
}
return tokens;
}
}
}
今天愉快。
答案 1 :(得分:0)
除了没有添加额外的h3e
类和枚举之外,这里的答案与Tokens
几乎相同。我们可以将字符串视为一个字符数组,获取所有右括号和右括号的索引,然后从它们之间获取子字符串:
private static IEnumerable<string> GetItems(string text)
{
var items = new List<string>();
var openBraceIndexes = text.Select((chr, index) => new { chr = chr, index })
.Where(item => item.chr == '{').ToList();
var closeBraceIndexes = text.Select((chr, index) => new { chr, index })
.Where(item => item.chr == '}').ToList();
if (openBraceIndexes.Count != closeBraceIndexes.Count)
{
throw new FormatException("text contains an unequal number of open and close braces");
}
for (int i = 0; i < openBraceIndexes.Count; i++)
{
var startIndex = openBraceIndexes[i].index + 1;
var length = closeBraceIndexes[i].index - startIndex;
items.Add(text.Substring(startIndex, length).Trim());
}
return items;
}