【问题标题】:Split a string by spaces using regex使用正则表达式按空格分割字符串
【发布时间】:2017-06-27 14:11:23
【问题描述】:

假设我有一个字符串 str = "a b c d e"str.split(' ') 给了我一个元素数组 [a,b,c,d,e]。 我如何使用正则表达式来获得这个匹配?

例如: str.match(/some regex/) 给出 ['a','b','c','d','e']

【问题讨论】:

    标签: node.js regex coffeescript


    【解决方案1】:

    String.split() 支持正则表达式作为参数;

    String.prototype.split([separator[, limit]])

    let str = 'a b c d e';
    str.split(/ /);
    // [ 'a', 'b', 'c', 'd', 'e' ]
    
    let str = 'a01b02c03d04e';
    str.split(/\d+/);
    // [ 'a', 'b', 'c', 'd', 'e' ]
    

    【讨论】:

      【解决方案2】:

      根据您的用例,您可以尝试const regex = /(\w+)/g;

      这会捕获任何单词(与 [a-zA-Z0-9_] 相同)字符一次或多次。这假设您可以在空格分隔的字符串中包含超过一个字符的项目。

      这是我在 regex101 中制作的示例:

      const regex = /(\w+)/g;
      const str = `a b c d efg  17 q q q`;
      let m;
      
      while ((m = regex.exec(str)) !== null) {
          // This is necessary to avoid infinite loops with zero-width matches
          if (m.index === regex.lastIndex) {
              regex.lastIndex++;
          }
      
          // The result can be accessed through the `m`-variable.
          m.forEach((match, groupIndex) => {
              console.log(`Found match, group ${groupIndex}: ${match}`);
          });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-07
        • 2017-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-02
        • 1970-01-01
        • 2014-11-06
        相关资源
        最近更新 更多