q3d
q3d

Reputation: 3523

Match rest of string with regex

I have a string like this

ch:keyword
ch:test
ch:some_text

I need a regular expression which will match all of the strings, however, it must not match the following:

ch: (ch: is proceeded by a space, or any number of spaces)
ch: (ch: is proceeded by nothing)

I am able to deduce the length of the string with the 'ch:' in it. Any help would be appreciated; I am using PHP's preg_match()

Edit: I have tried this:

preg_match("/^ch:[A-Za-z_0-9]/", $str, $matches)

However, this only matches 1 character after the string. I tried putting a * after the closing square bracket, but this matches spaces, which I don't want.

Upvotes: 3

Views: 19510

Answers (4)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

Try this regular expression:

^ch:\S.*$

Upvotes: 3

dfsq
dfsq

Reputation: 193261

$str = <<<TEXT
ch:keyword
ch:test
ch:
ch:some_text
ch: red
TEXT;

preg_match_all('|ch\:(\S+)|', $str, $matches);

echo '<pre>'; print_r($matches); echo '</pre>';

Output:

Array
(
    [0] => Array
        (
            [0] => ch:keyword
            [1] => ch:test
            [2] => ch:some_text
        )

    [1] => Array
        (
            [0] => keyword
            [1] => test
            [2] => some_text
        )

)

Upvotes: 2

Ninja
Ninja

Reputation: 5142

preg_match('/^ch:(\S+)/', $string, $matches);
print_r($matches);

\S+ is for matching 1 or more non-space characters. This should work for you.

Upvotes: 4

Joseph Silber
Joseph Silber

Reputation: 219938

Try using this:

preg_match('/(?<! +)ch:[^ ].*/', $str);

Upvotes: 0

Related Questions