regex 为字符串中的符号数组给予空间

3zwjbxry  于 2023-08-08  发布在  其他
关注(0)|答案(3)|浏览(91)

考虑到每个符号总是在字符串的开头或结尾,我们希望在每个sgin之前或之后给一个空格,以便作为一个单词:
所需的结果被注解,如您所见,我的函数有问题:

modify('you always have to wake up?'); // you always have to wake up ? 

modify('...you always have to wake up'); // ... you always have to wake up

modify('...you always have to wake up?!'); // ... you always have to wake up ?!

function modify(string) {
    const sgins = ['?', '!', '...', '?!', '!?', '!!', '.'];
  for (let a = 0; a < sgins.length; a++) {
    const split = string.split(sgins[a]);
    string = string.replaceAll(sgins[a], ` ${sgins[a]} `).trim();
  }
  console.log(string);
}

字符串
你会怎么做?

6tr1vspr

6tr1vspr1#

你可以使用一个简单的正则表达式:

string.replace(/$[?!.]+/, '$& ');

字符串
表示将所有连续的?!.字符替换为字符串开头的字符加空格。最后也是一样。

modify('you always have to wake up?'); // you always have to wake up ? 

modify('...you always have to wake up'); // ... you always have to wake up

modify('...you always have to wake up?!'); // ... you always have to wake up ?!

function modify(string) {
   string = string.replace(/^[?!.]+/, '$& ').replace(/[?!.]+$/, ' $&');
   console.log(string);
}


如果你需要精确的前缀,你可以构建regexp:

modify('you always have to wake up?'); // you always have to wake up ? 

modify('...you always have to wake up'); // ... you always have to wake up

modify('...you always have to wake up?!'); // ... you always have to wake up ?!

function modify(string) {

  const sgins = ['?', '!', '...', '?!', '!?', '!!', '.'];

  const options = sgins.sort((a, b) => b.length - a.length).map(prefix => [...prefix].map(c => '\\' + c).join('')).join('|');

  string = string.replace(new RegExp('^(' + options + ')'), '$1 ').replace(new RegExp('(' + options + ')$'), ' $1');
  
  console.log(string);
}

new9mtju

new9mtju2#

首先,我不会使用split()对你说实话。我会这样写,但这不是最佳代码。这是不是所有情况下,我不得不更换一些迹象你的阵列工作.如果你想让它完美,那么你必须为很多不同的情况编写程序,所以代码会更大一些。例如,如果已经有空间了呢?等等

function modify(string) {
  let didEnd = false;
  let didStart = false;
    
  const sgins = ['?!', '!?', '!!', '!', '?', '...', '.'];
  for (let a = 0; a < sgins.length; a++) {
    if (string.startsWith(sgins[a]) && !didStart) {
      string = string.replace(sgins[a], `${sgins[a]} `);
      didStart = true;
    }
    if (string.endsWith(sgins[a]) && !didEnd) {
      string = string.replace(sgins[a], ` ${sgins[a]}`);
      didEnd = true;
    }
  }
  console.log(string);
}

modify('you always have to wake up?');
modify('...you always have to wake up'); 
modify('...you always have to wake up?!');

字符串

6l7fqoea

6l7fqoea3#

作为替代方案,您可以使用带有全局匹配/g的模式和2个捕获组。
在回调函数中,检查组1或组2是否要在前面或后面添加空格。

const regex = /^([?!.]+)|([?!.]+)$/g;

字符串

modify('you always have to wake up?'); // you always have to wake up ? 
modify('...you always have to wake up'); // ... you always have to wake up
modify('...you always have to wake up?!'); // ... you always have to wake up ?!

function modify(string) {
  const regex = /^([?!.]+)|([?!.]+)$/g;
  console.log(string.replace(regex, (_, g1, g2) => g1 ? g1 + " " : " " + g2));
}

相关问题