简体   繁体   English

如何使用JavaScript正则表达式匹配换行符?

[英]How do I match across line breaks with JavaScript regular expressions?

I have this expression: 我有这样的表达:

$(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.

How can I fix this? 我怎样才能解决这个问题?

. does not match linebreaks by default. 默认情况下与换行符不匹配。 Usually, the s (called singleline or dotall ) modifier changes that. 通常, s (称为singlelinedotall )修饰符会改变它。 Unfortunately, it is not supported by JavaScript. 不幸的是,JavaScript不支持它。

There is (a slightly verbose) trick to get around that. 有一个(一个稍微冗长的)技巧来解决这个问题。 The character class [\\s\\S] matches any space and any non-space character. 字符类[\\s\\S]匹配任何空格和任何非空格字符。 Ie 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

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, ie it matches any character not in the empty set). 或者,(仅在JavaScript中)您可以使用“蜡烛运算符” [^] ,它也匹配任何单个字符(因为它是空字符类的否定,即它匹配不在空集中的任何字符)。 Whether you find that more or less readable is a matter of taste I guess: 无论你发现或多或少的可读性都是一个品味问题,我想:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM