【问题标题】:Regex to replace single or multiple occurrence of hyphen正则表达式替换单个或多个出现的连字符
【发布时间】:2017-10-12 02:34:08
【问题描述】:

我在下面写了用连字符或反向转换空格的函数

  1. 带连字符的空格str.trim().replace(/\s+/g, '-')
  2. 带空格的连字符str.replace(/\-/g,' ')

但是现在我试图用双连字符替换单个连字符,我不能使用第 1 点函数,因为它转换单个/多个出现而不是单个。

有没有什么方法可以编写在单个公式中执行 3 次操作的正则表达式

  1. 将正斜杠转换为下划线replace(/\//g, '_')
  2. 用单个连字符转换空格
  3. 用多个连字符转换单个连字符

例如 正则表达式 1 更改

"Name/Er-Gourav Mukhija" into "Name_Er--Gourav-Mukhija"

regex 2 反过来。

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    您可以使用回调函数代替替换字符串。这样您就可以一次指定和替换所有字符。

    const input = 'Name/Er-Gourav Mukhija';
    const translate = {
      '/': '_',
      '-': '--',
      ' ': '-',
    };
    const reverse = {
      '_': '/',
      '--': '-',
      '-': ' ',
    };
    
    // This is just a helper function that takes
    // the input string, the regex and the object
    // to translate snippets.
    function replaceWithObject( input, regex, translationObj ) {
      return input.replace( regex, function( match ) {
        return translationObj[ match ] ? translationObj[ match ] : match;
      } );
    }
    
    function convertString( input ) {
      // Search for /, - and spaces
      return replaceWithObject( input, /(\/|\-|\s)/g, translate );
    }
    
    function reverseConvertedString( input ) {
      // Search for _, -- and - (the order here is very important!)
      return replaceWithObject( input, /(_|\-\-|\-)/g, reverse );
    }
    
    const result = convertString( input );
    console.log( result );
    console.log( reverseConvertedString( result ) );

    【讨论】:

      【解决方案2】:

      不可能编写进行条件替换(即 a->b、c->d)的正则表达式公式。相反,我会尝试创建两个语句来替换“”->“--”和“/”->“_”。

      您可以将现有代码用于这两种操作。我建议将来使用this site 来构建和测试正则表达式。

      【讨论】:

      • Regexr 在 javascript regexp 版本中存在一些问题。更好地使用regex101
      【解决方案3】:

      考虑var str = "Name/Er-Gourav Mukhija"

      1. 要将正斜杠转换为下划线,如您所述,请使用replace(/\//g, '_')
      2. 要使用单个连字符转换空格,请使用replace(/\s+/g, '-')
      3. 要将单连字符转换为双连字符,请使用replace(/\-/g, '--')

      这三个可以组合成:

      str.replace(/\//g, '_').replace(/\s+/g, '-').replace(/\-/g, '--')

      【讨论】:

        【解决方案4】:

        您应该使用循环一次完成所有操作:

        str = str.split("");
        var newStr = "";
        str.forEach(function (curChar) {
          switch(curChar) {
            case " ":
              newStr += "-";
              break;
            case "/":
              newStr += "_";
              break;
            case "-":
              newStr += "--";
              break;
            default:
              newStr += curChar;
          } 
        });
        str = newStr;
        

        如果您愿意,可以随意将其转换为函数。我也没有让它做相反的事情,但你需要做的就是用 switch () 语句中的 case 字符串替换赋值字符串。

        没有办法用正则表达式来做这一切,因为你以后的正则表达式至少在一种情况下会覆盖你的第一个正则表达式,不管你怎么写。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-06-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多