Regex替换括号C#中的逗号
本文关键字:Regex 替换 | 更新日期: 2023-09-27 18:29:01
我很难只在括号内替换这个字符串的逗号:
选择distinct ''n(''+rtrim(ent.custno)+'-'+rtrim(ent.company)+'')作为客户,ent.phone,0作为curr,''n''n(从billmast中选择SUM(billmast.balance)作为余额,其中billmast.billid=ent.entid和ent.cid='abis'和billmast.balance0和billmast.invdate>dateadd(day,-60,getdate())以及billmast.invdate0和billmast.invdate>dateadd(day,-90,getdate())以及billmast.invdate0和billmast.invdate>dateadd(day,-120,getdate())以及billmast.invdate0和billmast.adddate
我尝试过的:
//// replaces nothing
//cols = Regex.Replace(cols, ",*(?=[^(]*''))", m => m.Value.Replace(",", ";"));
//// adds semi-colon between each character inside parentheses
//cols = Regex.Replace(cols, ",*(?=[^(]*''))", ";");
//// replaces nothing
//cols = Regex.Replace(cols, ",(?=[^(]*''))", ";");
//// replaces nothing
//cols = Regex.Replace(cols, ",(?=[^(]*''))", m => m.Value.Replace(",", ";"));
//// replaces nothing
//cols = Regex.Replace(cols, @",(?=[^()]*'))", ";");
//// replaces nothing
//cols = Regex.Replace(cols, @",(?=[^()]*'))", m => m.Value.Replace(",", ";"));
//// adds semi-colon between each character inside parentheses
//cols = Regex.Replace(cols, ",*(?=[^()]*''))", ";");
// replaces all commas with semi-colon - not just ones in parentheses
//cols = Regex.Replace(cols, ",(?![^(]*''))", ";");
在许多其他事情中。
,(?![^(]*'')
似乎在下面的演示中有效,但在C中无效#https://regex101.com/r/mO1bZ5/1
假设你的括号是成对的,可以嵌套(平衡),并且你需要替换这些平衡括号内的所有逗号,你可以使用正则表达式来匹配这些子字符串,并用匹配计算器替换逗号:
cols = Regex.Replace(cols, @"'((?>[^()]|(?<c>)'(|(?<-c>)'))*(?(c)(?!))')", m => m.Value.Replace(",", ";"));
请参阅IDEONE演示
问题是您的字符串包含嵌套的括号。您的模式必须考虑到这一事实,并像下面的示例字符串一样描述最终嵌套的括号:(aaaaa,bbbbb(cccc(dddd)eeee)ffff)
,以确保右括号是好的。
string pattern = @",(?=(?>[^()]+|'((?<depth>)|')(?<-depth>))*?(?(depth)(?!))'))";
cols = Regex.Replace(cols, pattern, ";");
命名捕获(此处不捕获任何内容)的作用类似于计数器。
每次遇到左括号时,计数器递增,每次遇到右括号时,计数递减。最后,条件(?(depth)...)
检查计数器(在示例中命名为depth
),如果它不为null,它会强制模式失败,并使用始终失败的断言:(?!)
(字面意思是:后面没有任何东西)。
详细信息:
,
(?=
(?> # open an atomic group: important because a simple
# non-capturing group(?:[^()]+)* may cause a catastrophic
# backtracking if the end of the pattern doesn't succeed.
[^()]+ # all that is not a parenthesis
|
'( (?<depth>) # a opening parenthesis increments the counter
|
') (?<-depth>) # a closing parenthesis decrements the counter
)*? # a non-greedy quantifier is used because the group must
# be repeated until the end of the pattern succeeds
# (it prevents the regex engine to match all the string
# and to give back characters until the pattern succeeds)
(?(depth) (?!) ) # check the counter and forces to fail when not null
')
)