11

I have the string id=0515 abcdefghijk. With the goal of matching only the 0515, I created the following regex: ((?<=id=).*(?<=\s)).

My result was 0515 (with the space between the id and letters included).

If I change my regex to the following (replace the '\s' with an actual space), I get my intended result of just the numbers with no space at the end: ((?<=id=).*(?= ))

Is it okay to use an actual space instead of the character code? Or does my regex need more work?

Kervvv
  • 751
  • 4
  • 14
  • 27
  • 2
    Yes, for your case a space works. `\s` matches any whitespace [character](https://stackoverflow.com/a/21067350/6622817) (spaces, tabs, carriage returns, new lines...) – Taku Dec 11 '17 at 23:41

1 Answers1

19

The difference is that specifically matches a space, while \s will match any whitespace character (\r, \n, \t, \f and \v).

While there's nothing wrong with using a space in a regex, considering you're only looking for the digits, why not simply use \d (which matches any digit, 0 to 9)?

This will cut down your regex signifcantly, and achieve the same result, as can be seen here.

Hope this helps! :)

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
  • I now understand the differences, makes sense. Also not all the time will id have all numbers, otherwise using `/d` indeed would be a simpler approach. Thank you. – Kervvv Dec 27 '17 at 08:42