16

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?

1
  • 2
    Yes, for your case a space works. \s matches any whitespace character (spaces, tabs, carriage returns, new lines...) Commented Dec 11, 2017 at 23:41

1 Answer 1

22

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! :)

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.