Javascript regexp matching notation separated by non-numeric characters

I would like to get all numbers consisting of 4 digits. Before and after there must be 2 non-character characters or no characters at all.

This is what I still have. In this example, only β€œ0000” is the correct result, but it also matches 1234, 4567, 5678.

What am I missing?

Js fiddle: http://jsfiddle.net/M8FYm/3/

Source:

<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <title>Regex test</title>
    <script type="text/javascript">
        $(document).ready(function(){
            pattern = '(\D{2})?('+'([0-9]{4})'+')(\D{2})?';

            var regexp = new RegExp(pattern, "g");
            var string = $('.test').html();

            while (match = regexp.exec(string)) {
                console.log(match);
            }
        })
    </script>
</head>
<body>
    <p class="test">
        1234 4567 67
        0000  345
        456 23  0000
        12345678
    </p>
</body>
</html>
+4
source share
2 answers
var test = 
"1234 4567 67\n" + 
"0000  345\n" +
"456 23  0000\n" +
"12345678";

test.match(/(^|\D{2})\d{4}(\D{2}|$)/gm)
// => ["0000  ", "  0000"]

Regex , 2 , 4 , , 2 -. /m ^ $ , .

+2

, jsfiddle. (2) (m) , :

/\D{2}[0-9]{4}\D{2}/gm

:

0000
0000

example: http://jsfiddle.net/Ebxfj/

+1

Source: https://habr.com/ru/post/1528977/


All Articles