Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match upto x regex or y regex

I currently have this:

^(.+)\(\w+\)|^(.+)\s\(\d{3}\:\d{3}\s\-\s\d{3}\:\d{3}\)

The #1 it only matches Foo's
#2 Foo has which is correct
#3 does match foo but it's in the 3rd array item [2]:

3rd array output:
    (
        [0] => Foo (100:200 - 300:400)
        [1] => 
        [2] => Foo
    ) 


The bold is what I'm trying to match:
Foo's (match11) this (100:200 - 300:400) the end #1
Foo has (not_matched) (100:200 - 300:400) the end #2
Foo (100:200 - 300:400) the end #3
note: im not trying to match the #1,#2,#3 at the end of each line, thats just for reference.

If "(100:200 - 300:400)" is found then get any text in front of it, elseif "(not_matched) (100:200 - 300:400)" found then get any text in front of it, else get text in front of "(100:200 - 300:400)"

The elseif part "(not_matched) (100:200 - 300:400)" can be identified as it only has 1 white space between the 2 round brackets of not_matched and (100:200 - 300:400)


Edit:

This is what i'v come up with which does seem to work, though it requires some workarounds in php to be useful.

(.+)\s\(\w+\)\s\(|(.+)\s\(\d{3}\:\d{3}\s\-\s\d{3}\:\d{3}\)

Working example: http://www.rubular.com/r/NSpGcnyg0p
For some reason it doesn't seem to save my example, so you will have to copy/paste it in.

But the regex doesn't have a direct match on each of them, thats why I have to remove the empty array element in php so that I get the result in the [1] element.

Can anyone see what I'm doing wrong in my regex?

like image 408
Mint Avatar asked Nov 15 '22 03:11

Mint


1 Answers

Try this:

^.*?(?=\s*(?:\(not_matched\)\s)?\(\d+:\d+\s*-\s*\d+:\d+\))

or, in PHP:

if (preg_match(
    '/^                   # Anchor the match at start of line
    .*?                   # Match any number of characters lazily
    (?=                   # until just before the following:
     \s*                  # - optional whitespace
     (?:                  # - the following group:
      \(not_matched\)\s   #    - literal (not_matched), followed by 1 whitespace
     )?                   #   (which is optional)
     \(\d+:\d+\s*-\s*\d+:\d+\) # a group like (nnn:mmm - ooo:ppp)
    )                     # End of lookahead assertion
    /x', 
    $subject, $regs)) {
    $result = $regs[0];
} else {
    $result = "";
}
like image 200
Tim Pietzcker Avatar answered Dec 19 '22 11:12

Tim Pietzcker