A regular expression is a tool used to describe string matching patterns, widely applied in programming languages, text editors, and command-line tools. By combining characters and operators, regular expressions enable precise matching of specific string patterns, facilitating search, replace, and extraction operations.
In regular expressions, square brackets define character sets, while parentheses are used for grouping. In development, it is often necessary to extract content inside parentheses from strings. Below, we use PHP as an example to demonstrate how to achieve this.
PHP's built-in preg_match function is used for regular expression matching. Its main function is to search for content matching the pattern within a string. If found, it returns 1; otherwise, it returns 0 or FALSE. The main parameters of preg_match include:
<span class="fun">preg_match($pattern, $subject, $matches);</span>
Here, $pattern is the regular expression pattern, $subject is the string to search, and $matches stores the match results.
The example below shows how to use a regular expression to match all content inside parentheses in a string:
$pattern = '/\((.*?)\)/';
$subject = 'This is a (example) string with (multiple) pairs of (parentheses).';
preg_match_all($pattern, $subject, $matches);
print_r($matches[1]);
Explanation: The \((.*?)\) in $pattern matches any content enclosed by parentheses, where .*? is a non-greedy match ensuring the smallest possible content inside the parentheses.
The preg_match_all function finds all occurrences that match the pattern within the string. The results are stored in the $matches array, with $matches[1] containing all contents inside the parentheses.
Array
(
[0] => example
[1] => multiple
[2] => parentheses
)
The result shows the code successfully extracted all content inside the parentheses from the string.
Regular expressions are powerful tools for string matching and extraction. In PHP, using preg_match or preg_match_all functions with appropriate regular expressions allows easy extraction of content inside parentheses. The expression /\((.*?)\)/ demonstrated here efficiently matches text within parentheses and is suitable for various practical use cases.