【问题标题】:how to remove white space at the beginning and end of a regular expression?如何删除正则表达式开头和结尾的空格?
【发布时间】:2015-01-15 11:51:42
【问题描述】:

我为我的标记语言创建了一个 javascript 解析器。 我希望标签和内容之间没有这样的空格:

__underline a sentence __and more. 
(or correctly : __underline a sentence__ and more.)

到:

<u>underline a sentence</u> and more.

但结果是第一种情况:

<u>underline a sentence </u>and more.

我的代码:

var tabML = ['\'','*','_'],
    tabHTML = ['em','strong','u']
    tag, char;
for(var i=0; i<tabML.length; i++){
    tag = tabHTML[i]; char = tabML[i];
    regex = new RegExp(char+char+'(.+)'+char+char, 'ig');
    txt = txt.replace(regex, '<'+tag+'>$1</'+tag+'>');
}

谢谢。

【问题讨论】:

    标签: javascript regex parsing replace


    【解决方案1】:

    使用下面的正则表达式,然后将匹配的字符替换为&lt;u&gt;$1&lt;/u&gt;

    __\s*(.*?)\s*__\s*
    

    DEMO

    > var s1 = "__underline a sentence __and more."
    undefined
    > var s2 = "__underline a sentence__ and more."
    undefined
    > s1.replace(/__\s*(.*?)\s*__\s*/g, '<u>$1</u> ')
    '<u>underline a sentence</u> and more.'
    > s2.replace(/__\s*(.*?)\s*__\s*/g, '<u>$1</u> ')
    '<u>underline a sentence</u> and more.'
    

    【讨论】:

    • 谢谢。只需在 2 个第一个下划线后添加 \s* : __\s*(.*?)\s*__\s*
    【解决方案2】:
    __(.*?)[ ]*__[ ]*
    

    试试这个。替换为&lt;u&gt;$1&lt;/u&gt;。查看演示。

    https://regex101.com/r/tX2bH4/5

    var re = /__(.*?)[ ]*__[ ]*/gm;
    var str = '__underline a sentence __and more.\n__underline a sentence__ and more.';
    var subst = '<u>$1</u> ';
    
    var result = str.replace(re, subst);
    

    【讨论】:

      猜你喜欢
      • 2021-09-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2020-05-07
      • 2021-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多