【问题标题】:Splitting strings by both "\\" and "." with regex [duplicate]用 "\\" 和 "." 分割字符串使用正则表达式 [重复]
【发布时间】:2019-09-28 21:45:54
【问题描述】:

我有以下字符串:

  var str = 'd:\\projects\\my_project\\dist\\js\\example.js'

我想将字符串拆分成数组如下:

['d:', 'projects', 'my_project', 'dist', 'js', 'example', 'js']

如何使用 str.split(regex) 做到这一点?我需要什么正确的正则表达式?

已经尝试过str.split('(\.|\\)') 和str.split('\.|\\')(即不带括号)

'\.' 和 '\\' 在单独通过时都可以工作,但不能组合使用。

请帮助我的正则表达式大师!

【问题讨论】:

    标签: javascript arrays regex string split


    【解决方案1】:

    您将字符串传递给split(),您需要传递RegExp()。

    注意:如果您将使用/(\.|\\)/) 之类的括号,则结果还将包括. 和\\

    var str = 'd:\\projects\\my_project\\dist\\js\\example.js'
    console.log(str.split(/\.|\\/))

    【讨论】:

      【解决方案2】:

      将正则表达式传递给split:

      var str = 'd:\\projects\\my_project\\dist\\js\\example.js';
      const res = str.split(/\.|\\/);
      console.log(res);
      .as-console-wrapper { max-height: 100% !important; top: auto; }

      您正在传递一个字符串 - 它正在寻找一个无法找到的文字模式 .|\。正则表达式 (regex) 使用斜杠 /,而不是引号 ' 或 "。

      【讨论】:

      • 非常感谢。我已经尝试过投票,但不确定您是否获得了赞誉,因为我的声望不到 15。
      • @mepley 如果您不能投票,您可以随时通过单击勾号将最合适的答案标记为“已回答”
      • @NickParsons 谢谢!好的,现在几乎达到 15 声望了大声笑
      【解决方案3】:

      其他答案已经说明您需要将正则表达式传递给String.split(),而不是string。因此,或者,您可以使用这个正则表达式:/[\\.]/。这个正则表达式定义了一个Character Set:

      var str = 'd:\\projects\\my_project\\dist\\js\\example.js';
      console.log(str.split(/[\\.]/));
      .as-console {background-color:black !important; color:lime;}
      .as-console-wrapper {max-height:100% !important; top:0;}

      【讨论】:

      • 谢谢大家的帮助!试图给大家投票。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多