The trilogy of regular expressions should be: 1. Search; 2. Reference matched text (backward reference); 3. selectively Replace text.
Note that the regular expression implementation in most languages uses backward reference to represent a subpattern in search. Its syntax is "\ Number". In replacement, the syntax is "$ number ".
Replace the phone number format
Our telephone format is usually: (area code) telephone, for example: (0756) 8401132; now suppose we want to change all the telephone formats in the text to: 0756-8401132. We can do this:
\((\d{4})\)(\d{8})
Effect demonstration
(0756)82514769 (0756)83281314 (0756)88401132
This example code
function reg_replace(){var test = document.getElementById("test");var regex = /\((\d{4})\)(\d{8})/g;test.innerHTML = test.innerHTML.replace(regex,"$1-$2");}
If you see this in this article from the beginning, I believe this expression is not difficult for you. Note that here, the metacharacters "(" and ")" Are escaped, and, in the replacement result, we require that it not appear.
Additional reading
The topic list of this article is as follows:
- What is a regular expression?
- Getting started with regular expressions: match a Fixed Single Character
- Getting started with regular expressions: matching any single character
- Getting started with regular expressions: Use character groups
- Getting started with regular expressions: Use character ranges in character groups
- Getting started with regular expressions: Use of assense character groups
- Getting started with regular expressions: matching null characters
- Getting started with regular expressions: Match one or more characters
- Regular Expression: matches zero or multiple characters.
- Regular Expression entry: matches zero or one string.
- Getting started with regular expressions: Match fixed numbers of Characters
- Getting started with regular expressions: match the number of characters in a range
- Getting started with regular expressions: greedy matching
- Getting started with regular expressions: inert matching
- Entry to Regular Expressions: two matching Modes
- Getting started with regular expressions: match word boundaries
- Getting started with regular expressions: boundary definition and relativity
- Getting started with regular expressions: Match non-word boundaries
- Getting started with regular expressions: match the beginning and end of a text
- Entry to regular expression: submode
- Regular Expression entry: "or" Match
- Getting started with regular expressions: replacing with referenced text
- Getting started with regular expressions: unmatched
- Regular Expression Summary: Regular Expressions in JavaScript
- Regular Expression Summary: advanced application of regular expressions in js