如何使用JavaScript正则表达式在换行符之间进行匹配? [英] How do I match across line breaks with JavaScript regular expressions?

查看:99
本文介绍了如何使用JavaScript正则表达式在换行符之间进行匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个表情:

$(document).ready(function(){
    $.validator.addMethod(
        "regex",
        function(value, element) {
            return this.optional(element) || /^(?!.*www)(?!.*http)(?!.*@)(?!.*\.com)(?!.*\.pt)(?!.*co\.uk).+$/i.test(value);
        },
        "Description field can not include e-mail and/or urls."
    );
    $("#regForm").validate();
});

如果我有这样的文本,由于换行而出现错误

If I have a text like this, I get an error, because of the line break

A Loja virtual possui uma vasta linha de bijouterias folheadas a ouro e prata. São produtos bastante procurados e com preços muito acessíveis(50% de desconto no atacado).
Ha mais de 10 anos no mercado de folheados.

Produtos de excelente qualidade.

如果我有此文本,没有换行符,则可以正常工作:

If I have this text, without line breaks, it works fine:

A Loja virtual possui uma vasta linha de bijouterias folheadas a ouro e prata. São produtos bastante procurados e com preços muito acessíveis(50% de desconto no atacado).Ha  mais de 10 anos no mercado de folheados.Produtos de excelente qualidade.

我该如何解决?

推荐答案

.默认情况下不匹配换行符.通常, s (称为 singleline dotall )修饰符可以更改此内容.不幸的是,JavaScript不支持它.

. does not match linebreaks by default. Usually, the s (called singleline or dotall) modifier changes that. Unfortunately, it is not supported by JavaScript.

有一个(稍微冗长的)技巧可以解决这个问题.字符类 [\ s \ S] 匹配任何空格和任何非空格字符.IE.任何字符.因此,您需要这样做:

There is (a slightly verbose) trick to get around that. The character class [\s\S] matches any space and any non-space character. I.e. any character. So you would need to go with this:

/^(?![\s\S]*www)(?![\s\S]*http)(?![\s\S]*@)(?![\s\S]*\.com)(?![\s\S]*\.pt)(?![\s\S]*co\.uk)[\s\S]+$/i

或者,(仅在JavaScript中)您可以使用蜡烛运算符" [^] ,它也匹配任何单个字符(因为它是空字符类的取反,即它匹配任何字符不在空集中).我想您是否觉得可读性或多或少都取决于品味:

Alternatively, (only in JavaScript) you can use the "candle operator" [^] which also matches any single character (since it's a negation of the empty character class, i.e. it matches any character not in the empty set). Whether you find that more or less readable is a matter of taste I guess:

/^(?![^]*www)(?![^]*http)(?![^]*@)(?![^]*\.com)(?![^]*\.pt)(?![^]*co\.uk)[^]+$/i

这篇关于如何使用JavaScript正则表达式在换行符之间进行匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆