/ / Javascript, regular expression: examples, checking regular expressions

Javascript, regular expression: examples, checking regular expressions

Before the advent of hypertext languages, but rather, beforethe moment it became clear that it was necessary not only to look for, but also to do it under certain conditions, in a specific place, with changed data, in the right quantities, the usual search and replace functions suited any sophisticated programmer. Masterpieces of search art were created in programming languages, and databases were refined in the form of sampling conditions, equipped with stored procedures, triggers and other means of sampling from bulky relational information compositions. The appearance of regular expressions did not lead to the revolution, but it turned out to be a useful and convenient means for searching and replacing information. For example, regular expressions of JavaScript email greatly simplify the registration of visitors, do not load the site by sending messages to non-existent addresses.

Say JavaScript is a regular expressionIt is impossible to think much better than thought sequences of indexOf () in the frame of conditional and cyclic operators, but it can be said that it made the script code compact but poorly understood by the uninitiated.

RegExp object = template + engine

Regular expressions are a template + engine.The first is the regular expression itself - the JavaScript object is RegExp, the second is the executor of the template that applies it to the string. The engines that implement regular expressions for each programming language are different. And although not all the differences are significant, it must be borne in mind, as well as the regular expression must be carefully checked before it is used.

javascript regular expression

Особая нотация при написании регулярных выражений quite convenient and effective enough, but requires care, accuracy and patience from the developer. Regular expression pattern notation needs getting used to. This is not a tribute to fashion, it is the logic of the implementation of the JavaScript regular expression mechanism.

Regular expression pattern

Two options are allowed:

var expOne = / abc * / i;

var expTwo = RegExp (“abc *”, “i”);

The first method is usually used. In the second case, quotation marks are used, because to use the character "", it must be escaped according to the general rules.

"i" is the flag for "case is not important." You can also use the flags "g" - "global search" and "m" - multi-line search.

The symbol "/" is used to denote a pattern.

Start and end of regular expression

Символ "^" определяет символ(ы), с которого the regular expression begins, and "$" determines which character (s) should be at the end. You should not experiment with them inside the expression, there they have a different meaning.

For example,

var eRegExp = new RegExp (cRegExp, "i");

var cRegRes = "";

var sTest = "AbcZ";

if (eRegExp.test (sTest)) {

cRegRes + = "- Yes";

} else {

cRegRes + = "- No";

}

var dTestLine = document.getElementById ("scTestLine");

dTestLine.innerHTML = "Expression /" + cRegExp + "/ for the string" "+ sTest +" "" + cRegRes.

In the "scTestLine" element there will be a result (the variable cRegExp has a corresponding value):

expression / ^ AbcZ $ / for the string "abcz" - Yes

If you remove the flag "i", the result will be:

expression / ^ AbcZ $ / for the string "abcz" - No

Regular expression content

A regular expression is a sequence of characters that is subject to search. The expression / qwerty / is looking for the entry of this particular sequence:

expression / qwerty / for the string "qwerty" - Yes

expression / qwerty / for the string "123qwerty456" - Yes

The symbol "^" changes the essence of the expression:

expression / ^ qwerty / for the string "123qwerty456" - No

expression / ^ qwerty / for the string "qwerty456" - Yes

Similarly for the end of line character.Regular expressions allow sequences: for example, [a-z], [AZ], [0-9] - all letters of the Latin alphabet in the specified register or numbers. Russian letters are also allowed to be used, but you should pay attention to the encoding of strings (where it is searched for, what is being searched for) and pages. Often Russian letters, as well as special characters, it is preferable to set codes.

When forming a regular expression, you canspecify options for the presence of certain characters in a particular place, while their number is set as follows: "*" = repeat 0 or more times; "+" = repeat 1 or more times; {1,} is the same as "+"; {n} = repeat exactly n times; {n,} = repeat n or more times; {n, m} = repeat from n to m times.

Используя квадратные скобки, можно указать character options from the set. It looks like this. [abcd] = [a-d] = any of the four characters: "a", "b", "c" or "d". You can specify the opposite. Any character except those specified in the set: [^ abcd] = any character except "a", "b", "c" or "d". "?" indicates that there may not be a character in this place. "." defines any character other than denoting a line break These are "n", "r", "u2028" or "u2029". The expression "s * | S *" = "[s | S] *" means searching for any character, including line breaks.

Simplified Regular Expression Options

The expression "[s | S] *" is a search for a space or its absence, that is, everything that is in the string. In this case, the symbol "s" means a space, and "S" - its absence.

Similarly, you can use "d" to search for a decimal digit, and "D" will find a non-numeric character. The designations "f", "r" and "n" correspond to form-feed, carriage return and line-feed.

The tab character is "t", the vertical one is "v". The designation "w" will find any Latin alphabet character (letters, numbers, underscore) = [A-Za-z0-9_].

The designation "W" is equivalent to [^ A-Za-z0-9_]. This means any character that is not a letter of the Latin alphabet, a number or the "_" sign.

Search for character "

Recommended wording and regular expression encoding

Any regular expression is important to carefully test on different variants of strings.

javascript regular expressions

С опытом создания регулярных выражений ошибок will be less, but nevertheless it should always be borne in mind that own knowledge of the rules of writing a regular expression may not correspond to reality, especially when the "regular" is transferred from one language to another.

Choosing between classics (exact indication) anda simplified version of a regular expression, it is better to prefer the first one. Indeed, in the classics it is always clearly indicated what is being sought and how. If there are Russian letters in the regular expression or in the search string, all strings and the page on which the JavaScript code that executes the regular expression should be converted to a uniform encoding is used.

When processing characters that do not belong to the Latin alphabet, it makes sense to consider specifying character codes, and not the characters themselves.

When implementing JavaScript search algorithms, a regular expression should be carefully checked. It is especially important to control the character encoding.

Regular expression parentheses

Square brackets give the character optionswhich must be or be absent in a certain place, and round - variants of sequences. But this is only a general rule. There are no exceptions to it, but there are many different options for applications.

var cRegExp = "[a-z] *. (png | jpg | gif)";

var eRegExp = new RegExp (cRegExp, "i");

var cRegRes = "";

var sTest = "picture.jpg";

if (eRegExp.test (sTest)) {

cRegRes + = "- Yes";

} else {

cRegRes + = "- No";

}

Results:

Expression / [aaaz] * .(png|jpg|gif)/ for the line "picture.jpg" - Yes

expression /^[a-d[[a-z[*..(png|jpg|gif)/ for the line "picture.jpg" - No

the expression /^[a-d[[a-z[*..(png|jpg|gif)/ for the line "apicture.jpg" - Yes

the expression /^[a-d[[a-z long.

It should be noted that everything, after which there is an asterisk, may be present zero times. This means that the "regular season" can work in unexpected ways at least.

javascript regular expressions examples

Check RegExp - testing email

In JavaScript, regular expressions get two methods, test and exec, and can be used in string objects (String) in their methods (functions): search, split, replace, and match.

The test method has already been demonstrated, it allows you to check the correctness of a regular expression. Method result: true / false.

Consider the following javascript regular expressions. Checking email from “difficult but certain”:

var eRegExp = / ^ (([^ <> () [] \.,;: s @ "] + (. [^ <> () [] \.,;: s @"] +) *) | ( ". +")) @ (([[0-9] {1,3}. [0-9] {1,3}. [0-9] {1,3}. [0-9] {1 , 3}]) | (([a-zA-Z-0-9] +.) + [A-zA-Z] {2,})) $ /;

for the line var sTest = "[email protected]" gives true, that is, this line is a valid email address. The test was carried out using the eRegExp.test (sTest) method.

Practical use: processing e-mail

The exec method on the output provides an array call:

var Result = RegEx.exec (Test);

cRegRes = "
" + aResult.length + "
";
for (var i = 0; i cRegRes + = aResult [i] + "
";
}

gives the following result:

9
[email protected]
Slava.Chip
Slava.Chip
.Chip
undefined
sci.by
undefined
sci.by
sci.

The remaining methods work similarly.It is recommended to check them yourself. It is desirable to work out the development and use of regular expressions in practice, copying the code is not always appropriate here.

Popular "regulars"

The provided JavaScript regex foreMail is not the only one, there are many simpler options. For example, /^ [w-. ]+@ [w- ]+. [a-z] [2,3 ]$/i. However, this option does not take into account all options for recording an email address.

Of course, you need to view the experience of colleagues,analyze their proposed methods before designing their own regular JavaScript expression. But there are some difficulties. Do not forget that in JavaScript regular expressions (examples of them when copying) can duplicate the essential characters: "", "/" or quotes. This will lead to an error that can be searched for.

It is important to take into account the usual "human aspect".After all, a formal JavaScript regular expression for a phone that can be a visitor (person) is indicated in various ways: 123-45-67, (29) 1234567, 80291234567 or +375291234567. And this is all the same number. The option of writing several templates is not always acceptable, and a rigid fixation of the rule for writing a number can create unnecessary inconvenience or limitations. The / ^ d [d () -] {4,14} d $ / i option is suitable for most cases of checking the phone number.

Если необходимо составить JavaScript регулярные expressions, only digits checking, even such a simple case requires clarification. It must consider an integer or fractional, exponential notation or regular, positive or negative. You can also take into account the presence of a currency symbol, the number of digits after the decimal point and the division of the integer part of a number into triads.

The expression / ^ d + $ / i checks only the numbers, while the expression /^d+.d+$/i allows you to use a period to indicate the fractional part of the number.

In javascript, regular expression checking canbe used to strictly indicate the format of the input data, which is important, in particular when entering questionnaires, passport data, legal addresses, etc.

Checking the date - just about complicated

javascript regex for email

Consider another JavaScript regular expressions.Examples for a date, like a number or a phone number are a choice between rigidity and flexibility. The date of the event is one of the essential data that you often need to enter. But fixing the input in a specific format: "dd-mm-yyyy" or "dm.yyy" often leads to customer dissatisfaction. The transition from the day-to-month input field, filled with the classic HTML form, may not take place when you enter only one digit, and entering the second one may cause difficulties. For example, 3 has already been entered in the day field, and the next number 2 does not replace the first one, and 32 is assigned to it, which naturally causes inconvenience.

Efficiency and convenience of regular expressionssignificantly depend on the overall construction of the dialogue with the visitor. In one case, to specify the date, it is advisable to use one form input field, in the other case, you need to provide different fields for the day, month, and year. But then there will be additional “code expenses” for checking the leap year, the number of months, the number of days in them.

javascript replace regular expressions

Replace search, regular expression memory

JavaScript replace (regular expressions)use the method of the String object and allow you to find the value and immediately change it. This is convenient for correcting input errors, editing the contents of form fields and for converting data from one presentation format to another.

var cRegExp = / ([a-i] +) s ([a-i] +) s ([a-i] +) / i; // search creates three "variables"

var sTest = "this article is good!";
var cRegRes = sTest.replace (cRegExp, "$ 2, $ 3, $ 1");

var dTestLine = document.getElementById ("scTestLine");

dTestLine.innerHTML = "The expression" + cRegExp + "for the line" "+ sTest +" "will be:" + cRegRes;

Result:

expression / ([a-i] +) s ([a-i] +) s ([a-i] +) / i for the line "this article is good!" it will turn out: article, good, this!

When executed, each pair of parentheses remembers the result in the "variable" $ n, where n is the number of the pair of brackets ($ 1, $ 2, ...). In contrast to the generally accepted, here the numbering of variables is from 1, not from 0.

javascript regular expressions email validation

General recommendations

Регулярное выражение упрощает код, но время на its development often matters. You can start working with simple constructions, then combine the made into more complex expressions. You can use various online services to test regular expressions or special local tools.

javascript regular expressions only numbers

The best option is to create your ownregular expression libraries and a proprietary tool for testing new developments. This is the best way to consolidate the experience and learn how to quickly create reliable and convenient designs.

Using character and string repetitions, i.e.special characters "*", "+" and curly brackets indicating the number of repetitions should be guided by the principles of simplicity and expediency. It is important to understand that the regular expression from the moment it starts working and until the result is obtained is entirely at the mercy of the browser engine used. Not all JavaScript languages ​​are equivalent. Each browser can add their own personal preferences in the interpretation of regular expressions.

Compatibility is not limited to pages and tables.stylesheets, it also relates to regular expressions. A page using JavaScript can only be considered debugged when it has successfully worked on various browsers.

JavaScript, String and RegExp

Rightfully work at the client level, that is, inbrowser visitor in javascript requires highly skilled developer A long time ago, it became possible to debug JavaScript code with the browser’s own tools or with the help of third-party extensions, code editors, and independent programs.

However, not in all cases the debugger canmanage and provide the developer with good support, quick error detection, detection of bottlenecks. Times when the computer was focused on computing, in the distant past. Now, special attention is paid to information, and string objects have begun to play a significant role. Numbers have become strings, and they manifest their true essence only at the right time and in the right place.

Regular expressions reinforce the capabilities of strings, but require proper respect for themselves. Debugging RegExp in the course of its work, even if it is possible to model it, is not a very interesting idea.

Understanding the structure and logic of the RegExp object, the meaning of the String object, the syntax and semantics of JavaScript is a sure guarantee of safe and reliable code, stable operation of each page and the site as a whole.