【问题标题】:Is there a regex to remove everything after comma in a string except first letter是否有正则表达式可以删除字符串中逗号后的所有内容,除了第一个字母
【发布时间】:2021-10-19 22:17:53
【问题描述】:

我试图从字符串中删除逗号后除第一个字母之外的所有字符。该字符串基本上是姓氏,名字。

例如:

Smith,John

我尝试如下,但它删除了逗号和逗号后的所有内容。

let str = "Smith,John";
str = str.replace(/\s/g, ""); // to remove all whitespace if there is any at the beginning, in the middle and at the end
str = str.split(',')[0];

预期输出:Smith,J

谢谢!

【问题讨论】:

  • 不确定您是否需要正则表达式本身,但另一种方式可能是str.substr(0, str.indexOf(",")+2)

标签: javascript regex typescript


【解决方案1】:

试试这个正则表达式:

\w+,\w

这匹配逗号前的一个或多个字符,然后只匹配 1 个字符。

这里是演示:https://regex101.com/r/bKpWt7/1

注意:\w 匹配来自[a-zA-Z0-9_] 的任何字符。

【讨论】:

    【解决方案2】:

    考虑到逗号周围的可选空格,以及逗号前的多个“名称”:

     *([^\s,][^,\n]*?) *, *([^\s,]).*
    
    • * 匹配可选空格
    • ( 捕获第 1 组
      • *([^\s,] 匹配可选空格并匹配除空白字符或, 之外的至少一个字符
      • [^,\n]*? 匹配除 , 或换行符非贪婪以外的任何字符
    • )关闭第一组
    • *, * 匹配可选空格之间的逗号
    • ([^\s,]) 捕获group 2,匹配除, 或空白字符以外的单个字符
    • .* 匹配该行的其余部分

    Regex demo

    在替换中使用第 1 组和第 2 组,$1,$2 之间有逗号

    const regex = / *([^\s,][^,\n]*?) *, *([^\s,]).*/;
    [
      "Smith,John Jack",
      "Smith Lastname , Jack John",
      "Smith  , John",
      " ,Jack"
    ].forEach(s => console.log(s.replace(regex, "$1,$2")));

    【讨论】:

      【解决方案3】:

      或者试试(,\w).* 和replace:

      let str = "Smith,John";
      str = str.replace(/(,\w).*/, '$1');
      console.log(str);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-16
        • 1970-01-01
        • 2022-11-07
        • 2021-07-11
        相关资源
        最近更新 更多