Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tilde operator in Regular expressions

Tags:

regex

php

pcre

People also ask

How do you denote special characters in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What is tilde in Postgres?

PostgreSQL supports following four operators for POSIX regular expression matching (also known as the tilde operator). The tilde operator returns true or false depending on whether or not a regular expression can match a string or a part thereof.


In this case, it's just being used as a delimiter.

Generally, in PHP, the first and last characters of a regular expression are "delimiters" to mark the start and ending position of a matching portion (in case you want to add modifiers at the end, like ungreedy, etc)

Generally PHP works this out from the first character in a string that is meant as a regular expression, matching the second occurence of it as the second delimiter. This is useful where you have an occurrence of the normal delimiter in the text (for example, occurences of / in the text) - this means you don't have to do awkward things.

Matching for "//" with the delimiter set to "/"

/\/\//

Matching for "//" with the delimiter of "#"

#//#


In this case, it doesn't mean anything. It is simply delimiting the start and end of your pattern. In PCRE (Perl Compatible Regular Expressions), which is what you're using with preg_* in PHP, the pattern is input along side the expression options, like so:

preg_match("/pattern/opt", ...);

However, the use of "/" as the delimiter in this case is arbitrary - although forward slash is popular, it can be replaced with anything. In your case, it's tilde.