Introduction to Regexes and Pattern mathing

xiaoxiao2021-03-06  49

1.2 Introduction to Regexes and Pattern Matching A regular expression is a string containing a combination of normal characters and special metacharacters or metasequences. The normal characters match themselves. Metacharacters and metasequences are characters or sequences of characters that represent ideas such as quantity, locations, or types of characters. The list in Section 1.2.1 shows the most common metacharacters and metasequences in the regular expression world. Later sections list the availability of and syntax for supported metacharacters for particular implementations of regular expressions. Pattern matching consists of finding a section of TEXT THAT THATED BY Underlying Code That Searchs The Text Is The REGULAR Expression Engine. You Can Guess The Results of Most Matches by Keeping Two Rules in Mind:

The earliest (leftmost) match wins Regular expressions are applied to the input starting at the first character and proceeding toward the last. As soon as the regular expression engine finds a match, it returns. (See MRE 148-149, 177-179. ) Standard quantifiers are greedy quantifiers specify how many times something can be repeated. The standard quantifiers attempt to match as many times as possible. They settle for less than the maximum only if this is necessary for the success of the match. The process of giving up characters and trying less-greedy matches is called backtracking (See MRE 151-153.) Regular expression engines have subtle differences based on their type There are two classes of engines:.. Deterministic Finite Automaton (DFA) and Nondeterministic Finite Automaton (NFA ). DFAS Are Faster But Lack Many of The Features of An Nfa, Such as Capturing, Lookaround, And Non-Greedy Quantifiers. In The Nfa World There Area Types: Traditional and Posix.dfa Engines

DFAs compare each character of the input string to the regular expression, keeping track of all matches in progress. Since each character is examined at most once, the DFA engine is the fastest. One additional rule to remember with DFAs is that the alternation metasequence is GREEDY. WHEN MORE THAN OPTION IN AN Alternation (foo | foobar) Matches, The LONGEST ONE IS SELECTED. SO, Rule # 1 Can Be Amended to read "The Longeest Leftmost Match Wins" (See MRE 155-156.)

Traditional NFA ENGINES

Traditional NFA engines compare each element of the regex to the input string, keeping track of positions where it chose between two options in the regex. If an option fails, the engine backtracks to the most recently saved position. For standard quantifiers, the engine chooses the greedy option of matching more text; however, if that option leads to the failure of the match, the engine returns to a saved position and tries a less greedy path The traditional NFA engine uses ordered alternation, where each option in the alternation is. tried sequentially. A longer match may be ignored if an earlier option leads to a successful match. So, rule # 1 can be amended to read "the first leftmost match after greedy quantifiers have had their fill." (See MRE 153-154. POSIX NFA ENGINES

POSIX NFA Engines work similarly to Traditional NFAs with one exception: a POSIX engine always picks the longest of the leftmost matches For example, the alternation cat | category would match the full word "category" whenever possible, even if the first alternative ( ". Cat ") Matched and APPEARED Earlier in The Alternation. (See MRE 153-154.)

1.2.1 Regex Metacharacters, Modes, and Constructs The metacharacters and metasequences shown here represent most available types of regular expression constructs and their most common syntax. However, syntax and availability vary by implementation. 1.2.1.1 Character representations Many implementations provide shortcuts to represent Some Characters That May Be difficult to input. (See MRE 114-117.)

Character Shorthands

Most implementations have specific shorthands for the alert, backspace, escape character, form feed, newline, carriage return, horizontal tab, and vertical tab characters. For example, / n is often a shorthand for the newline character, which is usually LF (012 octal) but can sometimes be CR (15 octal) depending on the operating system. Confusingly, many implementations use / b to mean both backspace and word boundary (between a "word" character and a non-word character). For these implementations, / b Means Backspace In a Character Class (a set of posible characters to match in the string) and Word boundary elsewhere.Octal escape: / num

REPRESENTS a TWO- Or Three- Octal Digit Number. For Example, / 015/012 Matches AN ASCII CR / LF Sequence.

HEX and UNICODE ESCAPES: / X Num, / x {Num}, / U Num, / U Num

REPRESENTS A Character Corresponding to a Hexadecimal Number. Four-Digit and Larger HEX NumBers CaResent The Range of Unicode Characters. For Example, / X0D / X0A Matches An ASCICI CR / LF Sequence.

Control Characters: / C Char

Corresponds to ASCII control characters encoded with values ​​less than 32. To be safe, always use an uppercase char-some implementations do not handle lowercase representations. For example, / cH matches Control-H, an ASCII backspace character.

1.2.1.2 Character classes and class-like constructs Character classes are ways to define or specify a set of characters. A character class matches one character in the input string that is within the defined set. (See MRE 117-127.)

Normal classes: [...] and [^ ...]

Character classes, [...], and negated character classes, [^ ...], allow you to list the character to match. A character class always matches one character class always matches one character. The - (Dash) INDICATES A RANGE OF CHARACTERS. TO INCLUDE The Dash In The list of character. for example, [az] matches any lowercase ascii letter.almost any character: dot (.)

USUALLY MATCHES ANY Character Except a newline. The match mode can offen be changed so much dot also matches newlines.

Class Shorthands: / w, / d, / s, / w, / d, / s

Commonly provided shorthands for digit, word character, and space character classes. A word character is often all ASCII alphanumeric characters plus the underscore. However, the list of alphanumerics can include additional locale or Unicode alphanumerics, depending on the implementation. For example, / D Matches A Single Digit Character and is Usually Equivalent To [0-9].

POSIX Character Class: [: alnum:]

POSIX Defines Several Character Classes That Can Be Used Only Wtem Expression Character Classes (See Table 1-1). For Example, [: Lower:], When Written As [: Lower:]], is equivalent to [az] in The Ascii Locale.

Unicode Properties, scripts, and blocks: / p {prop}, / p {prop}

The Unicode standard defines classes of characters that have a particular property, belong to a script, or exist within a block. Properties are characteristics such as being a letter or a number (see Table 1-2). Scripts are systems of writing, such as Hebrew, Latin, or Han. Blocks are ranges of characters on the Unicode character map. Some implementations require that Unicode properties be prefixed with Is or in. For example, / p {Ll} matches lowercase letters in any Unicode supported language, such As a or a. commicode Combining Character Sequence: / x

Matches a unicode base character followed by any number of unicode combining character / p {m} / p {m}. For example, / x matches è as well as the two two.

Table 1-1. POSIX Character Classes

Class Meaning alnum Letters and digits. Alpha Letters. Blank Space or tab only. Cntrl Control characters. Digit Decimal digits. Graph Printing characters, excluding space. Lower Lowercase letters. Print Printing characters, including space. Punct Printing characters, excluding letters and digits Upper Uppercase Letters. xdigit Hexadecimal Digits.

Table 1-2. Standard Unicode Properties (Continued)

Property meaning / p {l} letters. / P {ll} LowerCase letters. / P {lm} modifier letters. / P {lo} letters, other. These Have No Case and Are not considered modifiers. / P {lt} titlecase Letters. / p {lu} Uppercase Letters. / P {C} Control Codes and Characters Not in Other Categories. / P {CC} ASCII AND LATIN-1 Control Characters. / P {CF} Non-Visible Formatting Characters. / P {Cn} unassigned code point point point, such as company logos. / P {m} Marks Meant to Combine with base character to combine with base character to combine with base character, such as accept marks. / P {mc} modification characters that take up their own space. Examples include "vowel signs." / p {Me} Marks that enclose other characters, such as circles, squares, and diamonds. / p {Mn} characters that modify other characters, such as accents And umlauts. / p {n} Numeric Characters. / p {nd}. / p {nl} Letters That Are Numbers, Such As Roman Numerals, SUPERS, SYMBOLS, or NON-DIGIT Characters representing numbers. / p {p} puncture. / p {PC} Connecting, Such as an underscore. / P {pd} dashes and hyphens. / P {PE} closing puncture complementing / p {ps}. / P {pi} initial puncture, such as opening quotes. / P { PR {Po} {ps} Opening punctuation, such as opening punturation, such as opening punthese. / P {sc} currency. / P {SK } Combining characters represented as individual characters. / p {Sm} Math symbols. / p {So} Other symbols. / p {Z} Separating characters with no visual representation. / p {Zl} Line separators. / p {Zp} Paragraph SPARATORS. / P {Zs} Space Characters. 1.2.1.3 Anchors and Zero-Width Assertions Anchors and "Zero-Width Assertions" Match Positions in The Input String. (See MRE 127-133)

Start of line / string:. ^, / AMatches at the beginning of the text being searched In multiline mode, ^ matches after any newline Some implementations support / A, which only matches at the beginning of the text..

End of line / String: $, / z, / z

$ Matches at the end of a string. Some implementations also allow $ to match before a string-ending newline. If modified by multiline mode, $ matches before any newline as well. When supported, / Z matches the end of string or before a String-Ending Newline, Regardless of Match Mode. Some Implementations Also Provide / Z, Which Only Matches The end of the string, regardless of newlines.

Start of Match: / g

ITERATIVE MATCHING, / G MATCHES The POSITION WHERE The Previous Match Ended. OFTEN, this Spot Is Reset To The Beginning of A String ON A Failed Match.

Word Boundary: / b, / b, / <, />

Word boundary metacharacters match a location where a word character is next to a non-word character. / B often specifies a word boundary location, and / B often specifies a not-word-boundary location. Some implementations provide separate metasequences for start- and End-of-word boundaries, OFTEN / .

Lookahead: (? = ...), (?! ...)

Lookbehind: (? <= ...), (?

Lookaround constructs match a location in the text where the subpattern would match (lookahead), would not match (negative lookahead), would have finished matching (lookbehind), or would not have finished matching (negative lookbehind). For example, foo (? = BAR) Matches Foo in Foobar But Not Food. Implementations OFTEN LIMIT LOOKBEHIND Constructs To Subpatterns with a predetermined length.

1.2.1.4 Comments and MODE MODIFIERS MODIFIERS Are A Way to Change How The Regular Expression Engine Interprets A Regular Expression. (See MRE 109-112, 133-135.) Multiline Mode: M

Changes the behavior of ^ and $ to match next to newlines within the input string.

SINGLE-LINE MODE: S

Changes the behavior of. (Dot) To match all characters, include newlines, Within the input string.

Case-INSENSITIVE MODE: I

Treat As Identical Letters That Difer Only In Case.

Free-spacing mode: x

Allows for Whitespace and Comments WITHIN A Regular Expression. The whitespace and comments (Starting with "Are ignored by the regular expression engine.

Mode Modifiers: (? I), (? -I), (? Mod: ...)

Usually, mode modifiers may be set within a regular expression with (? Mod) to turn modes on for the rest of the current subexpression; (-mod?) To turn modes off for the rest of the current subexpression; and (mod:? ...) to Turn Modes On or Off Between The Colon and The Closing Parenthese. For example, "Use (? i: perl)" Use Perl "," Use Perl "," Use Perl ", ETC.

Comments: (? # ...) and #

In Free-Spacing Mode, # indeicates That the rest of the line is a comment. When Supported, The Comment SPAN (? # ...) can be embedded Anywhere in a regular expression, regardless of mode. For example ,. {0 , 80} (? # Field Limit IS 80 Chars) Allows You to make Notes About why you wheote. {0,80}.

Literal-text span: /q.../e

Escapes metachacters BetWeen / q and / e. For example, /q(.* )/e is the same as /( (/*/).

1.2.1.5 Grouping, capturing, conditionals, and control This section covers the syntax for grouping subpatterns, capturing submatches, conditional submatches, and quantifying the number of times a subpattern matches (See MRE 135-140.) Capturing and grouping parentheses:. ( ...) and / 1, / 2, ...

Parentheses perform two functions:. Grouping and capturing Text matched by the subpattern within parentheses is captured for later use Capturing parentheses are numbered by counting their opening parentheses from the left If backreferences are available, the submatch can be referred to later in the same.. Match with / 1, / 2, etc. the capture .

Grouping-only parentheses: (?: ...)

Groups a subexpression, possibly for alternation or quantifiers, but does not capture the submatch This is useful for efficiency and reusability For example,.. (:? Foobar) matches foobar, but does not save the match to a capture group.

Named Capture: (? ...)

Performs capturing and grouping, with captured text later referenced by name For example, Subject:. (?. *) captures the text following Subject: to a capture group that can be referenced by the name subject.

Atomic grouping: (?> ...)

TEXT MATCHED WITHIN THE GROUP IS NEVER BACKTRACKED INTO, EVEN IF this Leads to a match failure. For example, (?> [Ab] *) / w / w matches aabbcc but not aabbaa.

Alternation: ... | ...

Allows several subexpressions to be tested Alternation's low precedence sometimes causes subexpressions to be longer than intended, so use parentheses to specifically group what you want alternated For example, / b.. (Foo | bar) / b matches either of the words foo or bar . Conital: (? If Then | ELSE)

The if is implementation dependent, but generally is a reference to a captured subexpression or a lookaround. The then and else parts are both regular expression patterns. If the if part is true, the then is applied. Otherwise, else is applied. For example (<)? foo (? (1)> | bar) Matches and foobar.

Greedy Quantifiers: *, ,?, {Num, Num}

The greedy quantifiers determine how many times a construct may be applied. They attempt to match as many times as possible, but will backtrack and give up matches if necessary for the success of the overall match. For example, (ab) matches all of Ababababab.

Lazy quantifiers: *?, ?, ??, {num, num}?

.

Possessive Quantifier: * , ,? , {Num, Num}

Possessive quantifiers are like greedy quantifiers, except that they "lock in" their match, disallowing later backtracking to break up the sub-match. For example, (ab) ab will not match ababababab.

转载请注明原文地址:https://www.9cbs.com/read-77040.html

New Post(0)