[Technology blog] JS regular live learning

Regular basic grammar

Regular expressions (Regular Expression) is a single complex number pattern string matching string conditions, for Chomsky type 3 grammar.

Mathematical definition:
Serial AB represents the set {αβ | α ∈ A, β ∈ B}
parallel A | B denotes the set {α | α ∈ A or α ∈ B}
subset A * represents a complex set {a, b} = { ε, a, b, aa, ab, bb ...}

Regular expressions can be resolved finite automaton in this definition.

repeat

  • '*' : [0,∞]
  • '+' :[1,∞]
  • {A, b}: repetitions range from a to b times

Escape

With other programming concepts, the escape has two effects:

  1. Special characters reserved to the normal predetermined character,
    such as "." And " " are regular in special sign, using the "" to achieve escape, such as ab represents "ab", a * b represents "A B"
  2. Convert normal character to represent the special meaning of the characters,
    such as "d" use "" after that "\ d" represents a number

Greed & lazy mode

  1. a. * b represent as many matches with a start to the end of the string b
  2. a. *? b represent as little as possible match to a start to the end of the string b

Javascript scene

grammar

    //1. string 操作的字符串
    //2. regex 正则表达式
    //3. replacement 需要替换的效果
    string.replace(regex,replacement)
    
    //demo— /g表示全局替换
    str = str.replace(/raw/g,"dealed");

problem

Call the API directly back garden blog content can not only be used directly with html parsing component react native of.
JS can use regular processing.

solve

Requirements: <a href="url"><img src = "url" border="0" onload="..."/></a>Replace<img src="url"/>

Pictures resolve

//$1表示第一个参数(.*?)匹配到的部分
function ConvertPicture(raw){
    let result = raw.replace(/<a href=(.*?) target="_blank"><img(.*?)<\/a>/g,'<img src=$1 alt="图片"/>');
    return result;
}

Hyperlinks resolve

Also, similar to other transformations.
Requirements: <a href="http://www.hao123.com" target="_blank">测试超链接</a>convert[测试超链接]("url")

function ConvertHref(raw){
    let result = raw.replace(/<a href=(.*?) target="_blank">(.*?)<\/a>/g,'["$2"]("$1")');
    return result;
}

Guess you like

Origin www.cnblogs.com/PureMan6/p/10982739.html