1

Can someone help me with the following Java regex expression? I've done some research but I'm having a hard time putting everything together.

The regex:

"^-?\\d+$"

My understandning of what each symbol does:

  1. " = matches the beginning of the line
  2. - = indicates a range
  3. ? = does not occur or occurs once
  4. \\d = matches the digits
  5. + = matches one or more of the previous thing.
  6. $ = matches end of the line

Is the regex saying it only want matches that start or end with digits? But where do - and ? come in?

Mark
  • 962
  • 1
  • 6
  • 17

3 Answers3

5

- only indicates a range if it's within a character class (i.e. square brackets []). Otherwise, it's a normal character like any other. With that in mind, this regex matches the following examples:

  • "-2"
  • "3"
  • "-700"
  • "436"

That is, a positive or negative integer: at least one digit, optionally preceded by a minus sign.

Green Cloak Guy
  • 18,876
  • 3
  • 21
  • 38
3

Some regex is composed, as you have now, the correct way to read your regex is :

  • ^ start of word
  • -? optional minus character
  • \\d+ one or more digits
  • $ end of word

This regex match any positive or negative numbers, like 0, -15, 558, -19663, ...

Fore details check this good post Reference - What does this regex mean?

YCF_L
  • 49,027
  • 13
  • 75
  • 115
3

"^-?\\d+$" is not a regex, it's a Java string literal.

Once the compiler has parsed the string literal, the string value is ^-?\d+$, which is a regex matching like this:

^    Matches beginning of input
-    Matches a minus sign
?      Makes previous match (minus sign) optional
\d   Matches a digit (0-9)
+      Makes previous match (digit) match repeatedly (1 or more times)
$    Matches end of input

All-in-all, the regex matches a positive or negative integer number of unlimited length.

Note: A - only denotes a range when inside a [] character class, e.g. [4-7] is the range of characters between '4' and '7', while [3-] and [-3] are not ranges since the start/end value is missing, so they both just match a 3 or - character.

Andreas
  • 138,167
  • 8
  • 112
  • 195