官术网_书友最值得收藏!

Removal of characters from a string

In this recipe, we will see how special characters and blanks may be removed from a text string comprising of a telephone number. We will create a program that will take as input the number containing blank spaces and special characters such as +, (, and ).

The replace statement along with suitable regular expressions will be used. Various regular expressions may work in this case. We will see two such expressions in this recipe.

How to do it...

For meeting the mentioned requirement, proceed as follows:

  1. Declare a parameter by the name number, consisting of 20 characters.
  2. The replace all occurrences is added having the regular expression [^\d].
    How to do it...

How it works...

The solution is based on searching all non-digit characters in the string and replacing them with blank. The negated operator (^) is used within the box brackets and the \d denotes the digits. We have used all occurrences, as this will replace all non-digits.

Suppose the user enters the number having + and parentheses and blank spaces.

How it works...

This will remove all special characters, as well as spaces, and will only display numbers.

How it works...

There's more...

Alternately, you may also use [0-9] in place of \d. The regex will be then be written as '[^0-9]'. In addition, it is important to include regex in the replace statement. Otherwise, instead of searching the pattern within the text, the system searches for [^\d] or [^0-9] in the text, and the desired results will not be achieved.

主站蜘蛛池模板: 湘乡市| 凤山县| 苍梧县| 鲁甸县| 禹州市| 平武县| 军事| 炎陵县| 收藏| 桂平市| 神木县| 通海县| 无锡市| 昭平县| 永州市| 安阳市| 来凤县| 贡觉县| 瑞丽市| 施甸县| 宣恩县| 临海市| 南部县| 苍溪县| 辽阳县| 读书| 新建县| 固原市| 南汇区| 郧西县| 芷江| 昌宁县| 南郑县| 黄浦区| 永平县| 雅安市| 杂多县| 日喀则市| 遵化市| 融水| 霍林郭勒市|