I am trying to split sentences with some exceptions to ignore cases like Mr. And Mrs. Etc... And add them to an array.
This worked in vanilla JS for me
/(?<!\sMrs)(?<!\sMr)(?<!\sSr)(\.\s)|(!\s)|(\?\s)/gm
Unfortunately React Native doesn't support the negative lookbehind.
Is there another way I can achieve the same result?
CodePudding user response:
I ended up doing this:
let str = "Hello Mr. Jackson. How are you doing today?"
let sentences = str
.replace(
/(!”\s|\?”\s|\.”|!\)]s|\.\)\s|\?\)|!"\s|\."\s|\.\s|!\s|\?\s|[.?!])\s*/g,
"$1|"
)
.split("|")
let arr = []
for (let i = 0; i < sentences.length; i ) {
if (sentences[i].includes("Mr.") | sentences[i].includes("Mrs.")) {
arr.push(sentences[i] " " sentences[i 1])
i
} else {
arr.push(sentences[i])
}
}
console.log(arr)
If anyone has a more efficient solution, let me know!
CodePudding user response:
You can create exceptions in the following way:
let str = "Hello Mr. Jackson. How are you doing today?"
let sentences = str.match(/(?:\b(?:Mrs?|Sr)\.\s|[^!?.]) [!?.]?/g).map(x => x.trim())
console.log(sentences)
The regex (see its online demo) matches
(?:\b(?:Mrs?|Sr)\.\s|[^!?.])
- one or more occurrences of\b(?:Mrs?|Sr)\.\s
-Mr
,Mrs
orSr
as whole words followed with.
and a whitespace char|
- or[^!?.]
- any single char other than?
,!
and.
[!?.]?
- an optional!
,?
or.
.