我正在寻找一个正则表达式,它可以删除匹配括号之间的空格,即 (
和 )
,除了引号内的空格('
或 "
)在方括号内。
我目前有正则表达式 \s+(?=[^(]*\))
,它会删除括号之间的所有空格。当引号中有空格时也是如此。
// My input
do something with(in = 1, text='some text with spaces' , text2="also has spaces")
// My current output
do something with(in=1,text='sometextwithspaces',text2="alsohasspaces")
// My desired output
do something with(in=1,text='some text with spaces',text2="also has spaces")
此外:
- 引号只能出现在括号内
'
'
文本中可以有"
:text='text with "inside'
,不带\
转义字符。"
"
文本中可以有'
:text="text with ' inside"
,不带\
转义字符。- 字符串中引号前无转义字符:
text='This is\"not There'
我知道有很多关于正则表达式模式的问题,但我找不到一个能解决问题的方法。在我尝试过的许多事情中,期望只找到 (
直到 '
或 "
与 \s+ 之间的内容(?=[^("]*[\)"])
,但仍然会在 "
和 "
之间找到空格。
有人能指出我正确的方向吗?
最佳答案
好吧,由于您有两种类型的引用,"
和'
,您必须处理引用的引用:
abc"def pqr' ijk" "klm ' xyz"
请注意,两个撇号都被引用,这就是为什么不起作用。与括号相同。我怀疑是否 简单的正则表达式可以在这里提供帮助,但有限状态机可以:
private static string RemoveSpaces(string value) {
if (string.IsNullOrEmpty(value))
return value;
bool inQuotation = false;
bool inApostroph = false;
int bracketCount = 0;
int escapeCount = 0;
StringBuilder result = new StringBuilder(value.Length);
foreach (char c in value) {
if (inQuotation) {
result.Append(c);
inQuotation = c != '"' || (escapeCount % 2 != 0);
}
else if (inApostroph) {
result.Append(c);
inApostroph = c != '\'' || (escapeCount % 2 != 0);
}
else {
if (c != ' ' || bracketCount <= 0)
result.Append(c);
if (c == '(')
bracketCount += 1;
else if (bracketCount == ')')
bracketCount -= 1;
inQuotation = c == '"' && (escapeCount % 2 == 0);
inApostroph = c == '\'' && (escapeCount % 2 == 0);
}
escapeCount = c == '\\' ? escapeCount + 1 : 0;
}
return result.ToString();
}
演示:
string test =
@"do something with(in = 1, text='some text with spaces' , text2=""also has spaces"")";
Console.WriteLine(RemoveSpaces(test));
结果:
do something with(in=1,text='some text with spaces',text2="also has spaces")
关于c# - 删除括号内的空格(引号内的文本除外),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63474283/