你的第一个函数几乎是正确的。只需删除代表“全局”的'g'标志(编辑)并提供一些上下文来找到第二个'r'。
编辑:之前没有看到它是第二个'r',所以添加了'/'。在使用regEx参数时需要使用\/来转义'/'。感谢你们的支持,但我错了,所以我会修复并为那些有兴趣更好地理解正则表达式基础知识的人增加更多细节,但这将有效:
mystring.replace(/\/r/, '/')
现在开始进行冗长的解释:
在阅读/编写正则表达式模式时,请考虑以下方面:<一个字符或一组字符>后跟着<一个字符或一组字符>,再后跟着<...>。
在正则表达式中,<一个字符或一组字符>可以是一个一个地定义:
/each char in this pattern/
读作e,然后是a,然后是c等等...
或者单个的<a字符或一组字符>可以被描述为字符类:
/[123!y]/
//any one of these
/[^123!y]/
//anything but one of the chars following '^' (very useful/performance enhancing btw)
或者可以扩展到匹配一定数量的字符(但在顺序模式方面仍然最好将其视为单个元素):
/a{2}/
//precisely two 'a' chars - matches identically as /aa/ would
/[aA]{1,3}/
//1-3 matches of 'a' or 'A'
/[a-zA-Z]+/
//one or more matches of any letter in the alphabet upper and lower
//'-' denotes a sequence in a character class
/[0-9]*/
//0 to any number of matches of any decimal character (/\d*/ would also work)
将它们挤在一起:
var rePattern = /[aA]{4,8}(Eat at Joes|Joes all you can eat)[0-5]+/g
var joesStr = 'aaaAAAaaEat at Joes123454321 or maybe aAaAJoes all you can eat098765';
joesStr.match(rePattern);
//returns ["aaaAAAaaEat at Joes123454321", "aAaAJoes all you can eat0"]
//without the 'g' after the closing '/' it would just stop at the first match and return:
//["aaaAAAaaEat at Joes123454321"]
当然,我过于详细了,但我的意思只是这个:
/cat/
这是一系列由3个模式元素组成的序列(一个事物跟随着另一个事物,再跟随着另一个事物)。
这也是如此:
/[aA]{4,8}(Eat at Joes|Joes all you can eat)[0-5]+/
尽管正则表达式看起来很奇怪,但本质上它们都可以分解为按顺序依次跟随的一系列(可能是多个字符的)元素。这是一个基本点,但我花了很长时间才理解它,所以我在这里进行了过度解释,因为我认为这会帮助提问者和其他新手更好地理解正则表达式中发生的事情。阅读/编写正则表达式的关键是将其分解成这些部分。