正则表达式:查找子字符串以字符串开头和结尾并替换子字符串中的单词

Regex: Find substring starts with AND end with from a string and replace a word from substring

可能的输入:

输入1:

Hi John, I have recently..

输入2:

 hi , I have...

输入3:

 Hi Hans, I have...

输入4:

Hi, I have...

我想要一个正则表达式来添加或替换名称。以 Hi 开头(忽略大小写)并以 , 结尾。 (仅替换第一次出现)

例如,如果我想将其替换为 David

输出:Hi David, I have recently..

^(\S+)\s*\S*(?=,)

您可以通过 David 使用 this.Replace。查看演示。

https://www.regex101.com/r/fJ6cR4/7

var re = /^(\S+)\s*\S*(?=,)/gmi; 
var str = 'Hi John, I have recently..\nhi , I have...\nHi Hans, I have...\nHi, I have...';
var subst = ' David'; 

var result = str.replace(re, subst);

试试这个 RegEx。只需在 </code> 之后添加 <code>space

var regX = /^(hi)(\s?([a-z]+)?)?(?=,.+)/igm; 
var str = 'Hi John, I have recently..\nhi , I have...\nHi Hans, I have...\nHi, I have...';
var sub = ' David';
var result = str.replace(regX, sub);