简体   繁体   中英

Using regex to match combination of words in the same in the same sentence in PHP

I would like to use regular expression to find certain combination of words from a phrase in php. I can't even get the regex expression part to work.

The sentence should match any phrase that has the words (proficient/proficiency/fluent) in (chinese/mandarin/cantonese) in the same sentence. So it would match "She is fluent in Chinese." and "His proficiency in Mandarin is excellent"

regex = (fluent)|(proficient)|(proficiency).*(chinese)|(mandarin)|(cantonese)

I can get it to match the word fluent but how to make it match both words in the same sentence before it is considered a match?

Your grouping is wrong, it should be rather

(fluent|proficient|proficiency)[^.]*(chinese|mandarin|cantonese)

[^.] ensures (naively) that the words occur within the same sentence. Also, don't forget the i flag to match title-cased words like Chinese .

((fluent)|(proficient)|(proficiency)).*((chinese)|(mandarin)|(cantonese))

您需要在括号中加上括号,如果您还想匹配整个句子,则需要执行以下操作

[.!?].*((fluent)|(proficient)|(proficiency)).*((chinese)|(mandarin)|(cantonese)).*[.!?]

If the order doesn't matter, you could use two regexp, the first for the first group and a second to match the second group. Than you match two times and if both hit, you got it.

In case you're dealing with a fluent text, I would try to split it in sentences.

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