Regular expression start, end

Asked

Viewed 207 times

7

I have two regular expressions:

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

Must return true for archives started by abc in the first and def in the second. In the two expressions the string must 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?

2 answers

13


You should wear a subpater (group enclosed in parentheses) with alternation (character | or pipe) in accordance with described in the manual (untranslated).

That way the regular expression stays like this:

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

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

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

  • 1

    it should escape . (dot) after the 20150430 :P

0

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

  • Shapes the different REGEX
    • /^abc.*_20150430\.txt$/
    • /^def.*_20150430\.txt$/
  • unite them by or
    • ^abc.*_20150430\.txt$|^def.*_20150430\.txt$

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

Whether working on regex101

But over time you take the reductions of and shortcuts, as well as reply from @Sanction.

  • That would be the same thing as what’s in the question, only this time with regular expression. It’s really a lazy form of beginners.

  • @Ivanferrer of phallus, but so it already reduces a command preg, and posted like this, because I’ve thought about if there are more regex, with 3, as well, if he wants to have all the results in the third argument of preg_match, not to make two regex and after a merge.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.