简体   繁体   中英

Regular Expression to match string after specific word until dot

I have a string

Dažikliai. Nepavojingas. Savybės: Geltonas ekstrahuojamas iš kurkumos, neapalo šaknies. Arba gaunamas sintezės būdu.

and I want to match a word after static string Savybės . until first dot.

So my output should be:

Geltonas ekstrahuojamas iš kurkumos, neapalo šaknies

Here what I try so far

"/^Savybės=*$/"

but this doesn't give any results.

You could use a positive lookbehind:

Regex101 example

(?<=Savybės:\s).*?(?=\.)

Input:

Dažikliai. Nepavojingas. Savybės: Geltonas ekstrahuojamas iš kurkumos, neapalo šaknies. Arba gaunamas sintezės būdu.

Matches:

Geltonas ekstrahuojamas iš kurkumos, neapalo šaknies


If you want to include the . character at the end:

Regex101 example

(?<=Savybės:\s).*?\.

Input:

Dažikliai. Nepavojingas. Savybės: Geltonas ekstrahuojamas iš kurkumos, neapalo šaknies. Arba gaunamas sintezės būdu.

Matches:

Geltonas ekstrahuojamas iš kurkumos, neapalo šaknies.

You do not need a lookbehind and lazy dot matching that are inefficient. You can just use a capturing group and a negated character class to match any character but a dot:

$re = '/\bSavybės:\s*([^.]*)/u'; 
$str = "Dažikliai. Nepavojingas. Savybės: Geltonas ekstrahuojamas iš kurkumos, neapalo šaknies. Arba gaunamas sintezės būdu."; 
preg_match($re, $str, $matches);
echo $matches[1];

See IDEONE demo (note the /u modifier, too)

The regex matches:

  • \\b - word boundary (so as not to match any word that contains "Savybės")
  • Savybės: - literal Savybės: character sequence
  • \\s* - 0 or more whitespace
  • ([^.]*) - capture group #1 that will hold our value matching 0 or more characters other than a literal .

It takes my regex 14 steps to return the valid match, and it takes (?<=Savybės:\\s).*?(?=\\.) 179 steps.

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