user2420424
user2420424

Reputation: 63

How to get number from string

I have the following string:

adsfsd gj3h34 sdfsdfs dfs fds 24 d[4sfsdfsd sdfwe32  [3

Could you please tell me how to retrieve only 24 using a regex expression from that string? I have no idea...

Other examples:

String:

asd3 [32/ 3vsry4 1 svsdv

Expected output:

1

String:

trolololol '3211= la4so25lr 978 cxz

Expected output:

978 

Upvotes: 1

Views: 62

Answers (1)

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51330

My understanding is that you're looking for a series of digits \d+ between spaces (\s).

You could write: \s\d+\s but it would capture the spaces, and wouldn't work if the number is at the very start or end of the string.

You could also write \b\d+\b using the word boundary assertion (\b) but it wouldn't work either because some characters aren't considered part of a word (you'd match 3 in [3 for instance).

A better approach is:

(?<!\S)\d+(?!\S)

Demo

  • (?<!\S) means not preceded by a non-space
  • (?!\S) means not followed by a non-space

\S means a character that's not whitespace, (?<!...) and (?!...) are negative lookarounds.

Both these conditions are satisfied at the start and end of strings.

Upvotes: 1

Related Questions