This article mainly introduces the analysis of predefined classes and boundaries for in-depth understanding of JS regular expressions. It has a certain reference value. Now I share it with you. Friends in need can refer to it.
Regular expressions provide predefined classes to match common character classes
Characters | Equivalent classes | Meaning |
---|---|---|
. | [^\r\n] | Except carriage return and line feed characters All characters |
[0-9] | Numeric characters | |
[^0-9] | Non-numeric characters | |
[\t\n\x0B\f\r] | White space character | |
[^\t\n\x0B\f\r] | Non-white space character | |
[a-zA-Z_0-9] | Word characters (letters, numbers, underscores) | |
[^a-zA-Z_0-9] | Non-word characters |
/ab\d/
Boundary
Meaning | |
---|---|
Start with xxx | |
End with xxx | |
Word boundaries | ##\B |
let text = 'This is a boy' let reg1 = /is/g let reg2 = /\bis\b/g text.replace(reg1, 'IS') // 没有使用单词边界\b区分,结果为:ThIS IS a boy text.replace(reg2, 'IS') // 使用了单词边界进行区分,结果为:This IS a boy
let text = 'This is a boy' let reg3 = /\Bis\b/g text.replace(reg3, 'IS') // ThIS is a boy
$ can perfectly solve this problem:
let text = '@123@abc@' let reg1 = /@/g text2.replace(reg1, 'Q') // 没有使用^和$,匹配了所有的@,结果为:Q123QabcQ let reg2 = /^@/g text.replace(reg2, 'Q') // 使用^匹配开头的@,结果为:Q123@abc@ let reg3 = /@$/g text.replace(reg3, 'Q') // 使用$匹配结尾的@,结果为:@123@abcQ
tips: In actual use,
^ needs to be written in front of the matching item, while $ Need to unload the rear of the match
In the case of multiple lines, use ^ and $
let text = '@123\n@456\n@789' let reg1 = /^@\d/g text.replace(reg1, 'Q') /* 由于换行实际上只是一个换行符字符,在正常模式下,依然看做一段字符 结果为: Q23 @456 @789 */ let reg2 = /^@\d/gm text.replace(reg2, 'Q') /* 添加了m进入多行模式: 结果为: Q23 Q56 Q89 */
The above is the entire content of this article. I hope it will be helpful to everyone's learning. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
In-depth understanding of JS regular expression range analysis
In-depth understanding of JS regular expressions Analysis of metacharacters and character classes
The above is the detailed content of In-depth understanding of the analysis of predefined classes and boundaries of JS regular expressions. For more information, please follow other related articles on the PHP Chinese website!