Home > Web Front-end > JS Tutorial > body text

JS forward and backward regular expression definition and usage examples

高洛峰
Release: 2017-01-09 15:46:31
Original
1145 people have browsed it

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>
Copy after login

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!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template