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

时间:2019-04-12 05:09:39

标签: string salesforce apex

在Apex中,我要删除字符串中除“ +”以外的所有特殊字符。该字符串实际上是电话号码。我已经完成了以下工作。

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

因此,它打印的是44597583130。 但我想保留正号+,因为它代表00。

有人可以帮我吗?

1 个答案:

答案 0 :(得分: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('/|-| ',''));

两种情况下的输出都相同

  

|调试| +44597583130

     

|调试| +44597583130

修改

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

| DEBUG | +0032497593140