Re – write what you want

For example, find a from a string

let str = 'asfaf1232'
let re = /a/
str.search(re)
Copy the code

Regex is about learning escapes, metacharacters, quantifiers, and options

Metacharacters []

[] represents a range, which occupies only one position and has three types:

  • You can choose any one
    • [abac123]
    • In this position, it could be A, B, C, 1, 2, 3
    • It can only be one
    • For example: / [ABC] c/a
    • The value can be AAC, ABC, or ACC
  • The scope of
    • [0-9]
    • [a-z]
    • [0-9a-z]
  • To rule out
    • [^345] Anything except 3, 4, 5
    • [^0-9] Exclude numbers
    • [^a-z] exclude all letters
    • [^0-9a-z] excludes all alphanumeric characters

[Simple example] : identify whether it is QQ number

/ / analysis
// Contains 5 to 11 digits
// The first digit is 1-9

/ / qq number
let str = "5123123"
let re = / ^ 1-9] [\ d {4, 10} $/

// Tests whether the re is correct
re.test(str) // true

Copy the code

options

  • g
    • Family Search all
  • i
    • Ignore case

escape

  • \d
    • Represents all numbers
    • [0-9]

quantifiers

The positional range quantifier comes after () in the re, which means grouping

  • {n}
    • Some exact value
    • a{5} aaaaa
    • (ab){5} ababababab
  • {n,m}
    • A certain range
    • A {3, 8} 3-8 a
  • {n,}
    • Minimum n, maximum infinite
    • A {4,} At least four AS
  • {,m}
    • At least 0, at most M
    • A {,4} has at least 0 AS and at most 4 as

The regular way

  • str.search(re)
    • Searches for the first occurrence of the result of a re match
    • If found, returns the number 1, if not found, returns -1
  • str.match(re)
    • Return an array
    • Generally, g will be added, otherwise only the first match will be returned
  • re.test(str)
    • Returns a Boolean value
    • There is a glitch that returns true if there is a required part of the string
    • If you want to verify that the entire string is valid, you add ^ $