Regular expression start, end

7

I have two regular expressions:

$exp1 = '/^abc.*\_20150430.txt$/'
$exp2 = '/^def.*\_20150430.txt$/'

It should return true for files started by abc in the first and def in the second. In both expressions the string should end with _20150430.txt . For what I need to do:

if(preg_match($exp1, $str) || preg_match($exp2, $str)) {
    // Do something
}

How do I do this in a single regular expression?

    
asked by anonymous 30.04.2015 / 20:49

2 answers

13

You must use a subpatern (group delimited with parentheses) with alternation (character | or pipe ) as described in the manual (without translation).

In this way the regular expression looks like this:

'/^(abc|def).*_20150430\.txt$/'

I saw that you escaped the underline ( \_ ), but this is not a special character within the regular expression, so you do not need to escape.

The extension point in the filename ( 430.txt ) should be escaped, as pointed out by @wryel, because it is a wildcard

    
30.04.2015 / 20:55
0

What could be done too, and is very much practiced by beginners is:

  • Forms the different REGEX
    • /^abc.*_20150430\.txt$/
    • /^def.*_20150430\.txt$/
  • join them or
    • ^abc.*_20150430\.txt$ | ^def.*_20150430\.txt$

Note that it interprets as two distinct validations, however in the same validation.

Be working at regex101

But over time one can take reductions from and the shortcuts, as well as the Sanction response .

    
14.12.2015 / 14:34