我想用空格分割字符串,除非字符串中的文本是双引号(“text”)或单引号('text')
我正在使用此功能:
public static string[] ParseKeywordExpression(string keywordExpressionValue, bool isUniqueKeywordReq)
{
keywordExpressionValue = keywordExpressionValue.Trim();
if (keywordExpressionValue == null || !(keywordExpressionValue.Length > 0))
return new string[0];
int idx = keywordExpressionValue.Trim().IndexOf(" ");
if (idx == -1)
return new string[] { keywordExpressionValue };
//idx = idx + 1;
int count = keywordExpressionValue.Length;
ArrayList extractedList = new ArrayList();
while (count > 0)
{
if (keywordExpressionValue[0] == '"')
{
int temp = keywordExpressionValue.IndexOf(BACKSLASH, 1, keywordExpressionValue.Length - 1);
while (keywordExpressionValue[temp - 1] == '\\')
{
temp = keywordExpressionValue.IndexOf(BACKSLASH, temp + 1, keywordExpressionValue.Length - temp - 1);
}
idx = temp + 1;
}
if (keywordExpressionValue[0] == '\'')
{
int temp = keywordExpressionValue.IndexOf(BACKSHASH_QUOTE, 1, keywordExpressionValue.Length - 1);
while (keywordExpressionValue[temp - 1] == '\\')
{
temp = keywordExpressionValue.IndexOf(BACKSHASH_QUOTE, temp + 1, keywordExpressionValue.Length - temp - 1);
}
idx = temp + 1;
}
string s = keywordExpressionValue.Substring(0, idx);
int left = count - idx;
keywordExpressionValue = keywordExpressionValue.Substring(idx, left).Trim();
if (isUniqueKeywordReq)
{
if (!extractedList.Contains(s.Trim('"')))
{
extractedList.Add(s.Trim('"'));
}
}
else
{
extractedList.Add(s.Trim('"'));
}
count = keywordExpressionValue.Length;
idx = keywordExpressionValue.IndexOf(SPACE);
if (idx == -1)
{
string add = keywordExpressionValue.Trim('"', ' ');
if (add.Length > 0)
{
if (isUniqueKeywordReq )
{
if (!extractedList.Contains(add))
{
extractedList.Add(add);
}
}
else
{
extractedList.Add(add);
}
}
break;
}
}
return (string[])extractedList.ToArray(typeof(string));
}
有没有其他方法可以做到这一点,还是可以优化这个功能?
例如,我希望拆分字符串
%ABC %% aasdf%aalasdjjfas“c:\ Document and Setting \ Program Files \ abc.exe”
到
%ABC%
%aasdf%
aalasdjjfas
“c:\ Document and Setting \ Program Files \ abc.exe”
答案 0 :(得分:6)
最简单的正则表达式,处理单引号和双引号:
("((\\")|([^"]))*")|('((\\')|([^']))*')|(\S+)
var regex = new Regex(@"(""((\\"")|([^""]))*"")|('((\\')|([^']))*')|(\S+)");
var matches = regex.Matches(inputstring);
foreach (Match match in matches) {
extractedList.Add(match.Value);
}
所以基本上四到五行代码就足够了。
表达,解释说:
Main structure:
("((\\")|([^"]))*") Double-quoted token
| , or
('((\\')|([^']))*') single-quoted token
| , or
(\S+) any group of non-space characters
Double-quoted token:
( Group starts
" Initial double-quote
( Inner group starts
(\\") Either a backslash followed by a double-quote
| , or
([^"]) any non-double-quote character
)* The inner group repeats any number of times (or zero)
" Ending double-quote
)
Single-quoted token:
( Group starts
' Initial single-quote
( Inner group starts
(\\') Either a backslash followed by a single-quote
| , or
([^']) any non-single-quote character
)* The inner group repeats any number of times (or zero)
' Ending single-quote
)
Non-space characters:
( Group starts
\S Non-white-space character
+ , repeated at least once
) Group ends
答案 1 :(得分:2)
如果你不喜欢RegEx,这个方法应该能够拆分带引号的字符串,并忽略连续的空格:
public IEnumerable<string> SplitString(string input)
{
var isInDoubleQuote = false;
var isInSingleQuote = false;
var sb = new StringBuilder();
foreach (var c in input)
{
if (!isInDoubleQuote && c == '"')
{
isInDoubleQuote = true;
sb.Append(c);
}
else if (isInDoubleQuote)
{
sb.Append(c);
if (c != '"')
continue;
if (sb.Length > 2)
yield return sb.ToString();
sb = sb.Clear();
isInDoubleQuote = false;
}
else if (!isInSingleQuote && c == '\'')
{
isInSingleQuote = true;
sb.Append(c);
}
else if (isInSingleQuote)
{
sb.Append(c);
if (c != '\'')
continue;
if (sb.Length > 2)
yield return sb.ToString();
sb = sb.Clear();
isInSingleQuote = false;
}
else if (c == ' ')
{
if (sb.Length == 0)
continue;
yield return sb.ToString();
sb.Clear();
}
else
sb.Append(c);
}
if (sb.Length > 0)
yield return sb.ToString();
}
编辑:使用yield和StringBuilder将返回类型更改为IEnumerable
答案 2 :(得分:2)
我通过在字符串中使用\x27
和\x22
的十六进制值来转义单引号和双引号。它使模式的C#文字文本更易于阅读和操作。
正在使用IgnorePatternWhitespace
,因为它允许对模式进行评论以获得更好的可读性;不会影响正则表达式处理。
string data = @"'single' %ABC% %aasdf% aalasdjjfas ""c:\Document and Setting\Program Files\abc.exe""";
string pattern = @"(?xm) # Tell the regex compiler we are commenting (x = IgnorePatternWhitespace)
# and tell the compiler this is multiline (m),
# In Multiline the ^ matches each start line and $ is each EOL
# -Pattern Start-
^( # Start at the beginning of the line always
(?![\r\n]|$) # Stop the match if EOL or EOF found.
(?([\x27\x22]) # Regex If to check for single/double quotes
(?:[\x27\x22]) # \\x27\\x22 are single/double quotes
(?<Token>[^\x27\x22]+) # Match this in the quotes and place in Named match Token
(?:[\x27\x22])
| # or (else) part of If when Not within quotes
(?<Token>[^\s\r\n]+) # Not within quotes, but put it in the Token match group
) # End of Pattern OR
(?:\s?) # Either a space or EOL/EOF
)+ # 1 or more tokens of data.
";
Console.WriteLine( string.Join(" | ",
Regex.Match(data, pattern)
.Groups["Token"]
.Captures
.OfType<Capture>()
.Select( cp => cp.Value )
)
);
/* Output
single | %ABC% | %aasdf% | aalasdjjfas | c:\Document and Setting\Program Files\abc.exe
*/
以上内容基于我撰写的以下两篇博文: