Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between an anchored regex and an un-anchored regex?

Tags:

regex

What is the difference between an anchored regex and an un-anchored regex?

Usage found here:

... These should be specified as a list of pairs where the first element is an un-anchored regex (in java.util.regex.Pattern syntax) against which the platform name is matched...

like image 772
sdgfsdh Avatar asked Mar 02 '17 13:03

sdgfsdh


People also ask

What do these anchor characters do in regex?

Anchors belong to the family of regex tokens that don't match any characters, but that assert something about the string or the matching process. Anchors assert that the engine's current position in the string matches a well-determined location: for instance, the beginning of the string, or the end of a line.

What are the types of regular expression?

There are also two types of regular expressions: the "Basic" regular expression, and the "extended" regular expression.

What does \\ mean in Java regex?

String regex = "\\."; Notice that the regular expression String contains two backslashes after each other, and then a . . The reason is, that first the Java compiler interprets the two \\ characters as an escaped Java String character. After the Java compiler is done, only one \ is left, as \\ means the character \ .

What are regex patterns?

A regular expression is a pattern that the regular expression engine attempts to match in input text. A pattern consists of one or more character literals, operators, or constructs.


1 Answers

Unanchored regex means a regex pattern that has no anchors, ^ for start of string, and $ for the end of string, and thus allows partial matches. E.g. in Java, Matcher#find() method can search for partial matches inside an input string, "a.c" will find a match in "1.0 abc.". The anchored "^a.c$" pattern will match an "abc" string, but won't find a match in "1.0 abc.".

Also, an unanchored regex may mean the code that handles the regex pattern does not check if the match is equal to full input string. E.g. in Java, Matcher#matches() method requires that the pattern must match the full input string and s.matches("a.c") will match an "abc" string, but won't find a match in "1.0 abc.".

Anchored regex means the pattern will only match a string if the whole string matches.

See Start of String and End of String Anchors for more information about anchors in regex.

like image 171
Wiktor Stribiżew Avatar answered Oct 09 '22 13:10

Wiktor Stribiżew