【问题标题】:How to keep case with RegExp?如何使用 RegExp 保持大小写?
【发布时间】:2014-12-20 03:41:45
【问题描述】:

在用 RegExp 替换单词时如何保持大小写?我正在使用这个表达式:

token = "word";
text = "The Cow jumped over the moon. And the Dish ran away with the Spoon.";
value = text.replace(/\b\w\b/g, token);
//value = text.replace(/\b\w{1,}\b/g, token.charAt(0) + token.charAt(token.length-1));

// 这会导致

value == "word word word word word word. word word word word word word word word.";

//我想要的是

value == "Word Word word word word word. Word word Word word word word word Word.";

编辑
reg exp 匹配每个单词。

【问题讨论】:

  • 我相信你需要运行两个正则表达式,一个用于大写单词,另一个用于非大写单词。你也必须更具体——如果你有一个“用勺子炒菜”怎么办?

标签: javascript regex actionscript-3


【解决方案1】:

您可以在替换函数中使用条件返回。

显式专有名词

只过滤以大写字母开头的单词:

token = "word";
text = "The Cow jumped over the moon. And the Dish ran away with the Spoon.";
value = text.replace(/\b\w+\b/g, function(instance) {
   if (instance.charAt(0) === instance.charAt(0).toUpperCase()) {
       return token.charAt(0).toUpperCase() + token.substr(1, token.length - 1);
   } else {
       return token;
   }
});

// Output: "Word Word word word word word. Word word Word word word word word Word."

混合大小写

如果您也想检测大小写混合,请使用条件instance !== instance.toLowerCase()(我将字符串更改为包含混合大小写的单词):

token = "word";
text = "The Cow juMped over the mOON. And the Dish ran away with the Spoon.";
value = text.replace(/\b\w+\b/g, function(instance) {
   if (instance !== instance.toLowerCase()) {
       return token.charAt(0).toUpperCase() + token.substr(1, token.length - 1);
   } else {
       return token;
   }
});

// Output: "Word Word Word word word Word. Word word Word word word word word Word."

【讨论】:

    【解决方案2】:

    你也可以像这样在正则表达式中做到这一点

    str = str.replace(/\b\w+\b/g, function(m){ 
       return /^[A-Z]/.test(m) ? "Word" : "word" 
    });
    

    【讨论】:

    • 您仍然使用正则表达式:/^[A-Z]/。此外,按空格分割不会检测到所有的分词(例如标点符号),甚至不会检测到所有的空白字符。
    【解决方案3】:

    我建议分两个阶段进行

    /\b[A-Z][a-z]*\b/Word/g
    

    然后

    /\b[a-z]*\b/word/g
    

    警告-

    • 这只会忽略 MixedCaseALLCAPS 的任何单词。
    • 此方法将破坏国际化/Unicode 支持等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-18
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      • 2021-03-21
      • 1970-01-01
      • 2013-04-29
      • 2017-05-24
      相关资源
      最近更新 更多