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

后端 未结 1 1882
迷失自我
迷失自我 2021-01-14 15:29

I have this expression:

$(document).ready(function(){
    $.validator.addMethod(
        \"regex\",
        function(value, element) {
            return thi         


        
1条回答
  •  迷失自我
    2021-01-14 16:23

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

    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
    

    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
    

    0 讨论(0)
提交回复
热议问题