The examples in this article describe the definition and usage of JS forward-lookback regular expressions. Share it with everyone for your reference, the details are as follows:
Definition
x(?=y) matches 'x' only when 'x' is followed by 'y'. This is called positive affirmation Find.
For example, /Jack(?=Sprat)/ will match 'Jack' only if it is followed by 'Sprat'. /Jack(?=Sprat|Frost)/ matches 'Jack' only if it is followed by 'Sprat' or 'Frost'. But neither 'Sprat' nor 'Frost' is part of the match.
x(?!y) matches 'x' only when 'x' is not followed by 'y'. This is called a forward negative search.
For example, /\d+(?!\.)/ matches a number only if the number is not followed by a decimal point. Regular expression /\d+(?!\.)/.exec("3.141") matches '141' but not '3.141'
form https://developer.mozilla.org/zh-CN/ docs/Web/JavaScript/Guide/Regular_Expressions
Example:
<html> <head> </head> <body> <input id="test" type="text" value="" /> <input id="test" type="text" value="" /> <input id="test" type="text" value="" /> <input id="test" type="text" value="" /> <input id="test" type="text" value="" /> <script> var testStr = "windows 95" /* 1 - 不带子表达式匹配 */ var testReg = /^windows .*$/ var result = testStr.match(testReg); console.log("/^windows .*$/="+result) // /^windows .*$/=windows 95 /* 2 - 带子表达式匹配 */ var testReg = /^windows (.*)$/ var result = testStr.match(testReg); console.log("/^windows (.*)$/="+result) // /^windows (.*)$/=windows 95,95 /* 3 - 带子表达式,不记录其匹配结果 */ var testReg = /^windows (?:.*)$/ var result = testStr.match(testReg); console.log("/^windows (?:.*)$/="+result) // /^windows (?:.*)$/=windows 95 /* 4 - 前瞻匹配,匹配位置,正匹配 */ var testReg = /^windows (?=95)95$/ var result = testStr.match(testReg); console.log("/^windows (?=.*)$/="+result) // /^windows (?=.*)$/=windows 95 /* 5 - 前瞻匹配,匹配位置,负匹配 */ var testStr = "windows me" var testReg = /^windows (?!95)me$/ var result = testStr.match(testReg); console.log("/^windows (?!\d*)$/="+result) // /^windows (?!d*)$/=windows me </script> </body> </html>
I hope this article will be helpful to everyone in JavaScript programming.
For more articles related to JS forward-lookback regular expression definitions and usage examples, please pay attention to the PHP Chinese website!