Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does +(?!\d) in regex mean?

Tags:

regex

I have also seen it as +$.

I am using

$(this).text( $(this).text().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") );

To convert 10000 into 10,000 etc.

I think I understand everything else:

  • (\d) - find number
  • (?=\d{3}) - if followed by 3 numbers
  • '+' - don't stop after first find
  • (?!\d) - starting from the last number?
  • /g - for the whole string
  • ,"$1," - replace number with self and comma
like image 679
seanjacob Avatar asked Jul 25 '12 11:07

seanjacob


People also ask

What is \\ w+ in Java regex?

\\w+ matches all alphanumeric characters and _ . \\W+ matches all characters except alphanumeric characters and _ . They are opposite.

What does \d mean in JavaScript?

The RegExp \D Metacharacter in JavaScript is used to search non digit characters i.e all the characters except digits. It is same as [^0-9]. Syntax: /\D/

What do you mean by the \d \w and \s shorthand character classes signify in regular expressions?

What do the \D, \W, and \S shorthand character classes signify in regular expressions? The \D, \W, and \S shorthand character classes match a single character that is not a digit, word, or space character, respectively.

What does \b mean in regex?

The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).


2 Answers

I think you're slightly misreading it:

  • (?=\d{3}) - if followed by 3 numbers

Note that the regexp is actually:

(?=(\d{3})+

i.e. you've missed an open paren. The entire of the following:

(\d{3})+(?!\d)

is within the (?= ... ), which is a zero-width lookahead assertion—a nice way of saying that the stuff within should follow what we've matched so far, but we don't actually consume it.

The (?!\d) says that a \d (i.e. number) should not follow, so in total:

  • (\d) find and capture a number.
  • (?=(\d{3})+(?!\d)) assert that one or more groups of three digits should follow, but they should not have yet another digit following them all.

We replace with "$1,", i.e. the first number captured and a comma.

As a result, we place commas after digits which have multiples of three digits following, which is a nice way to say we add commas as thousand separators!

like image 63
Asherah Avatar answered Oct 06 '22 22:10

Asherah


?! means Negative lookahead , it is used to match something not followed by something else, in your case a digit

like image 35
M. Abbas Avatar answered Oct 06 '22 21:10

M. Abbas