Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regexp in switch statement

People also ask

What is the use of RegExp?

Regular expressions are particularly useful for defining filters. Regular expressions contain a series of characters that define a pattern of text to be matched—to make a filter more specialized, or general. For example, the regular expression ^AL[.]* searches for all items beginning with AL.

How do you make a RegExp?

If you want to match for the actual '+', '. ' etc characters, add a backslash( \ ) before that character. This will tell the computer to treat the following character as a search character and consider it for matching pattern. Example : \d+[\+-x\*]\d+ will match patterns like "2+2" and "3*9" in "(2+2) * 3*9".

What is matching RegExp?

The regexp-match-positions function takes a regexp pattern and a text string, and it returns a match if the regexp matches (some part of) the text string, or #f if the regexp did not match the string. A successful match produces a list of index pairs.

What does RegExp do in JavaScript?

RegExp Object A regular expression is a pattern of characters. The pattern is used to do pattern-matching "search-and-replace" functions on text. In JavaScript, a RegExp Object is a pattern with Properties and Methods.


Switch-case statement works like if-elseif.
As well as you can use regex for if-elseif, you can also use it in switch-case.

if (preg_match('/John.*/', $name)) {
    // do stuff for people whose name is John, Johnny, ...
}

can be coded as

switch $name {
    case (preg_match('/John.*/', $name) ? true : false) :
        // do stuff for people whose name is John, Johnny, ...
        break;
}

Hope this helps.


No or only limited. You could for example switch for true:

switch (true) {
    case $a == 'A':
        break;
    case preg_match('~~', $a);
        break;
}

This basically gives you an if-elseif-else statement, but with syntax and might of switch (for example fall-through.)


Yes, but you should use this technique to avoid issues when the switch argument evals to false:

switch ($name) {
  case preg_match('/John.*/', $name) ? $name : !$name:
    // do stuff
}