简体   繁体   中英

Regular Expression get part of string

How can I get only the text inside "()" For example from "(en) English" I want only the "en". I've written this pattern "/\\(.[az]+\\)/i" but it also gets the "()";

Thanks in advance.

<?php

$string = '(en) English';

preg_match('#\((.*?)\)#is', $string, $matches);

echo $matches[1]; # en

?>

$matches[0] will contain entire matches string, $matches[1] will first group, in this case (.*?) between ( and ) .

What is the dot in your regex good for, I assume its there by mistake.

Second to give you an alternative to the capturing group answer (which is perfectly fine!), here is to soltution using lookbehind and lookahead.

(?<=\()[a-z]+(?=\))

See it here on Regexr

The trick here is, those lookarounds do not match the characters inside, they just check if they are there. So those characters are not included in the result.

(?<=\\() positive look behind assertion, checking for the character ( before its position

(?=\\) positive look ahead assertion, checking for the character ( ahead of its position

那应该做的。

"/\(([a-z]+)\)/i"

The easiest way is to get "/\\(([az]+)\\)/i" and use the capture group to get what you want.

Otherwise, you have to get into look ahead, look behinds

You could use a capture group like everyone else proposes

OR

you can make your match only check if your match is preceded by "(" and followed by ")". It's called Lookahead and lookbehind.

"/(?<=\().[a-z]+(?=\))/i"

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