gpt4 book ai didi

javascript - 通过 JavaScript 正则表达式纠正句子结构

转载 作者:行者123 更新时间:2023-11-28 21:19:16 25 4
gpt4 key购买 nike

下面我有一个句子和该句子desiredResult。使用下面的 pattern 我可以捕获需要更改为 t, tt T,但我不知道下一步该去哪里.

var sentence = "Over the candidate behaves the patent Then the doctor.";
var desiredResult = "Over the candidate behaves the patent, then the doctor.";
var pattern = /[a-z]\s[A-Z]/g;

如果前面的字母是小写,我想通过在除“I”之外的大写字母前添加逗号和空格来获得正确的句子。

最佳答案

在句子中使用 .replace() 并将替换函数作为第二个参数传递

var corrected = sentence.replace(
/([a-z])\s([A-Z])/g,
function(m,s1,s2){ //arguments: whole match (t T), subgroup1 (t), subgroup2 (T)
return s1+', '+s2.toLowerCase();
}
);

至于保留大写的I,有很多方法,其中之一:

var corrected = sentence.replace(
/([a-z])\s([A-Z])(.)/g,
function(m,s1,s2,s3){
return s1+((s2=='I' && /[^a-z]/i.test(s3))?(' '+s2):(', '+s2.toLowerCase()))+s3;
}
);

但是还有更多情况会失败,例如:他的名字是 Joe。WTF 是 What a Terrible Failure 的缩写。 等等。

关于javascript - 通过 JavaScript 正则表达式纠正句子结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6810131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com