简体   繁体   中英

Regex - word followed after another word

I have PHP app and I would like to get string "word" followed after another word. It can be followed by another strings.

  1. Hello, this is status: ok
  2. Hello, this is status: ok.
  3. Hello, this is status: ok and I like it.

I would like to always get the "ok" status. How to do that please?

I have:

preg_match('~status:\s(.*)(?=\s.*)?~', $text, $matches);

But is returns everything after status: .

You could do it using a positive-lookbehind and take every word character after it.

(?<=status:\s)(\\w+)

Demo

You could just replace (.*) with (\\w*) :

preg_match('~status:\s(\w*)~', $text, $matches);

Demo

Another way to fix your current approach would be to make the dot in (.*) lazy, and then also make a slight change to your current lookahead:

preg_match('~status:\s(.*?)(?=\s|$)~', $text, $matches);

You may ask why your current solution doesn't work?

If you see it matches a whitespace character after matching status: then matches up to end of line by .* then backtracks to find a match where a space exists. If a whitespace after ok doesn't exist immediately or somewhere later in string no matches is found. Solution:

status:\s+\K\w+

You don't need capturing groups and shouldn't quantify a lookahead either.

See live demo here

PHP code:

preg_match('~status:\s+\K\w+~', $text, $matches);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM