1

I have the following string:

findByHouseByStreetByPlain

How can I match to values after each "By". I have managed to find the first "By" value, but I can't get it going that it gives me all the matches for the value after "By".

0

4 Answers 4

3

Thsi regex should work for you:

<?php 
$ptn = "#(?:By([A-Za-z]+?))(?=By|$)#";
$str = "findByByteByHouseNumber";
preg_match_all($ptn, $str, $matches, PREG_PATTERN_ORDER);
print_r($matches);
?>

this will be the output:

Array
(
    [0] => Array
        (
            [0] => ByByte
            [1] => ByHouseNumber
        )

    [1] => Array
        (
            [0] => Byte
            [1] => HouseNumber
        )

)
Sign up to request clarification or add additional context in comments.

3 Comments

Can work but remember that this regex only matches if the string starts with a capital and is followed by small caps. For example, findByHouSeByStreet will not match
Well that's how it is supposed to be written in camel-case.. for more complex examples..
I interpreted that the seperator is "By"
1

Some use of lookahead will do it

By(.*?)(?=By|$)

In php this become

preg_match_all('/By(.*?)(?=By|$)/', $subject, $result, PREG_SET_ORDER);
for ($matchi = 0; $matchi < count($result); $matchi++) {
    for ($backrefi = 0; $backrefi < count($result[$matchi]); $backrefi++) {
        # Matched text = $result[$matchi][$backrefi];
    } 
}

1 Comment

Just add some grouping if you want to extract submatches
0

Try this code below:

$pattern = "/[^By]+/";
$string = "findByHouseByStreetByPlain";
preg_match_all($pattern, $string, $matches);
var_dump($matches);

2 Comments

It also match with the "find".
And will also fail with findByByte (for example)
0

my string is different:

HouseByStreetByPlain

then i use the following regex:

<?php 
$ptn = "/(?<=By|^)(?:.+?)(?=(By|$))/i";
$str = "HouseByStreetByPlain";
preg_match_all($ptn, $str, $matches);
print_r($matches);
?>

output:

Array
(
    [0] => Array
        (
            [0] => House
            [1] => Street
            [2] => Plain
        )

    [1] => Array
        (
            [0] => By
            [1] => By
            [2] => 
        )

)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.