如何在Delphi Rio中使用TRegEx实现点与逗号的双向互换?
使用TRegEx实现点与逗号的互换
Hey there! Let's replace that three-step AnsiReplaceStr approach with a cleaner TRegEx solution for swapping dots (.) and commas (,) in Delphi Rio. Here's how to do it, including both a targeted function for dot/comma swaps and a generic version for any two symbols:
1. 针对点和逗号的专用互换函数
This is the simplest approach when you only need to swap . and ,:
uses System.RegularExpressions; function TformMain.SwapDotComma(const input: string): string; var MatchHandler: TMatchEvaluator; begin // 定义匹配后的替换逻辑:匹配到.就返回,,匹配到,就返回. MatchHandler := function(const Match: TMatch): string begin if Match.Value = '.' then Result := ',' else Result := '.'; end; // 用正则匹配所有的.或,,然后用上面的逻辑替换 Result := TRegEx.Replace(input, '[.,]', MatchHandler); end;
代码说明:
- 正则模式
[.,]是一个字符集,会匹配输入字符串中所有的.或,。 TMatchEvaluator匿名函数让我们可以动态决定每个匹配字符的替换值——再也不需要像原来那样用_做临时占位符了!
2. 通用版:交换任意两个符号
如果你需要一个可复用的函数,能交换任意两个符号(不只是.和,),这里有个更稳健的版本,能正确处理正则特殊字符:
uses System.RegularExpressions; function TformMain.SwapSymbols(const input, symbolA, symbolB: string): string; var MatchHandler: TMatchEvaluator; RegexPattern: string; begin // 转义符号,避免正则元字符(如*, +, ^)导致匹配错误 RegexPattern := TRegEx.Escape(symbolA) + '|' + TRegEx.Escape(symbolB); MatchHandler := function(const Match: TMatch): string begin if Match.Value = symbolA then Result := symbolB else Result := symbolA; end; Result := TRegEx.Replace(input, RegexPattern, MatchHandler); end;
为什么这个版本更安全?
TRegEx.Escape会把正则中有特殊含义的符号(比如$、(或?)转义为字面量,这样你交换这类符号时也不会破坏匹配规则。- 你可以像这样调用它:
SwapSymbols('100,200.00', ',', '.'),就能得到想要的100.200,00结果。
对比原来的实现
你原来的AnsiReplaceStr方法需要对字符串做三次遍历(用占位符避免覆盖),而TRegEx方案只需要一次遍历,效率更高,代码也更易读——对后续维护代码的人来说友好很多。
别忘了把System.RegularExpressions添加到uses子句里,Delphi Rio自带这个单元,不需要额外安装库!
内容的提问来源于stack exchange,提问作者Wisnu Widiarta
相关产品推荐
相关产品推荐

