简体   繁体   中英

ruby regex split string by . but not if its part of an word contained in an exclusion list

I want to split sentences by a specific char but just if this char isnt used as a part of a word that is contained in an exclusion list. For example I want to split the sentence by a fullstop "." but I just if its not used after "Dr" or "Prof". For example:

"Im a Dr. of Physics and my Name is Sheldon Cooper. Im working at the University of Pasadena."

So the regex should just split by the fullstop after "Cooper" but not after the "Dr".

You can use negative lookbehind:

a = "Im a Dr. of Physics and my Name is Sheldon Cooper. Im working at the University of Pasadena."
a.split(/(?<!Dr|Prof)\./)
#=> ["Im a Dr. of Physics and my Name is Sheldon Cooper", " Im working at the University of Pasadena"]

You can define titles separately. There's no other way to do that. You should set like this: Dr|Prof|Assoc

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