Methods that may be used in regular expressions

Time:2020-10-31

This article mainly explains the methods used by regularization

First of all, let’s start with a random string:

 let content = 'gabgAjklbgadlkjgbajkdgbAjldgbadg'

The first is a simple method that doesn’t require regularization

indexOf

If you use a simple match STR or intercept the matched text, I will use the str.indexOf (SearchValue, [fromindex]), the index of the first value will be returned if the result is matched, or – 1 if not,
At present, compared with two cases, regular is a little more complicated. That is, the G global matching and I in the regular are not case sensitive. If we only judge the matching case, we can make the judgment by converting STR and SearchValue to lowercase() lowercase,
If you are only using to find whether a single continuous character exists in the target STR, it is recommended to use indexof(),

//Tolowercase() is case sensitive
content.toLowerCase().indexOf('aj') // 4
//If you want to get the number of all matches
let currentIndex = content.toLocaleLowerCase().indexOf('aj');
let indexArr = [];
for(var i = 0;i<content.length;i++) {
  if(currentIndex!=-1) {
    indexArr.push(currentIndex);
    currentIndex = content.toLocaleLowerCase().indexOf('aj',currentIndex+1)
  }
}
console.log(indexArr); // [4, 17, 23]

includes

There is also an easy way to use in ES6 str.includes (searchvalue,[fromIndex])
The includes() method returns a Boolean value, and includes() can also determine undefined and Nan

content.toLowerCase().includes('aj') // true

Rarely used exec ()

The exec () method performs a search match in a specified string. Returns an array of results or null.
Usage: regexObj.exec (STR) returns NULL if there is no match and array if there is a value
Experience: the first parameter of the returned array is the first string matched to the regular, the second is the index of the first, and the third is your regular str

console.log(/aj/i.exec(content)) 
// ["Aj", index: 4, input: "gabgAjklbgadlkjgbajkdgbAjldgbadg", groups: undefined]

Simple test for matching test ()

The test () method performs a retrieval to see if the regular expression matches the specified string. Returns true or false
Usage: regexObj.test (str)
If the global flag is set for the regular expression, the execution of test() changes the lastindex property of the regular expression. If the test() method is executed continuously, the subsequent execution will start from the lastindex to match the string. (exec() also changes the lastindex property value of the regular itself)@1
Experience: this test is almost the same as indexof, which is used to determine whether there is any convenience. If the matching is more complicated, it is certainly better than indexof
Conclusion: it is simple and easy to use, only used to judge whether it matches

console.log(/aj/ig.test(content)); // true
@1

var regex = /aj/ig;
console.log(regex.test(content)); // true
console.log(regex.test(content)); // true
console.log(regex.test(content)); // true
console.log(regex.test(content)); // false

Here comes the best one: match ()

The match () method retrieves the result of a string matching the regular expression.
Usage: str.match (regexp) note that unlike the first two, match is a string method, and the first two are regexp methods
If you use the G flag, all results that match the full regular expression are returned; if you don’t use G, the return result is the same as exec

console.log(content.match(/aj/ig));
// ["Aj", "aj", "Aj"]

A string method search() that returns a Boolean value

The search () method is similar to test (), but it is a string method
Usage: str.search (regexp)
If the match is successful, search() returns the index of the first match of the regular expression in the string; otherwise, it returns – 1.
It is similar to the test () method of regular expressions.

console.log(content.search(/aj/ig));
// 4

Replace the regular matched fields

The replace () method returns a new string after replacing some or all matching patterns with the replacement value.
Grammar: str.replace (regexp|substr, newSubStr|function)
Regexp: regular expressions find what needs to be replaced
Substr: a string to be replaced. It is treated as an entire string, not as a regular expression. Only the first match is replaced.
Newsubstr: string used to replace the matching part of the first parameter in the original string. Some special variable names can be interpolated into the string. Details are availablehttps://developer.mozilla.org…
Function: a function used to create a new substring. The return value of this function will replace the result that the first parameter matches.
Summary: it is to replace the content of the first parameter to which the string matches, and return a new string with the content of the second parameter. If the first parameter is a string, only the first matching content can be replaced.
Note that one or all matches the new string replaced by the replacement pattern. The original string is not changed.

//Give a function that has been written to replace the highlighted one
function highLightKeyword(txt, searchValue) {
  If (! Txt) return ''; // TXT is the string to be replaced
  If (! SearchValue) return ''; // SearchValue is the content to be matched
  const keywords =  searchValue.split ('); // cut all the words into single words to form an array
  for (const keyword of keywords) { 
    txt = txt.replace(new RegExp(`(${keyword})`, 'ig'), `<strong>$1</strong>`);
  }
  return txt;
}

Recommended Today

Async await async download asynchronous code lock asynchronous cache

Async await async download asynchronous code lock asynchronous cache FTP asynchronous download code: /// ///Download files asynchronously /// ///FTP path ///User name ///Password ///File relative path public static async Task DownloadFileAsync(string ftpPath, string ftpUserId, string ftpPassword, string relativeFilePath) { FtpWebRequest request = null; try { LogTimeUtil log = new LogTimeUtil(); request = (FtpWebRequest)WebRequest.Create(new Uri(Path.Combine(ftpPath, relativeFilePath).Replace(“\\”, […]