Apex - 从字符串中删除除“+”之外的特殊字符

问题描述 投票:0回答:1

在Apex中,我想删除字符串中除“+”之外的所有特殊字符。这个字符串实际上是一个电话号码。我做了以下事情。

      String sampleText = '+44 597/58-31-30';
      sampleText = sampleText.replaceAll('\\D','');
      System.debug(sampleText);

所以它打印的是44597583130.但是我想保持符号+因为它代表00。

有人可以帮我弄这个吗 ?

string salesforce apex
1个回答
1
投票

可能的解决方案

String sampleText = '+44 597/58-31-30';
// exclude all characters which you want to keep 
System.debug(sampleText.replaceAll('[^\\+|\\d]',''));

// list explicitly each char which must be replaced    
System.debug(sampleText.replaceAll('/|-| ',''));

两种情况下的输出都是相同的

| DEBUG | 44597583130

| DEBUG | 44597583130

编辑

String sampleText = '+0032 +497/+59-31-40';
System.debug(sampleText.replaceAll('(?!^\\+)[^\\d]',''));

| DEBUG | 0032497593140

© www.soinside.com 2019 - 2024. All rights reserved.