Reputation: 43
I would like to get all the numbers composed of 4 digits. Before and after there should be 2 non digit characters or no characters at all.
This is what I have so far. In this example the correct result would be only "0000" 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>
Upvotes: 4
Views: 548
Reputation: 47189
The test string on your example here is not the same as the one on jsfiddle. By adding the correct spacing (2) and the multi-line modifier (m) to a revised regexp it should return the desired result:
/\D{2}[0-9]{4}\D{2}/gm
result:
0000
0000
example: http://jsfiddle.net/Ebxfj/
Upvotes: 1
Reputation: 3055
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"]
The Regex looks for either the start of a sentence or 2 non-digits, followed by 4 digits, followed by either the end of a sentence or 2 non-digits. The /m
modifier makes the ^
match beginning of lines and $
the ending of lines, not just the beginning and ending of the whole string.
Upvotes: 2