MagicHat
MagicHat

Reputation: 429

Regex match only numbers in a string

Example i need take only numbers in bellow strings.

lori ipsum 1, 2 e 3 dorm kietjiojwoijdej 162, 131 e 107 m²

lori fsdfsd ipsum 2 e 3 dormitórios fsrfsrfrfrfkietjiojwoijdej 162, 131 e 107 m²

lori ipsum dfs 3 dorm kidfsrfrfrffretjiojwoijdej 62, 13 e 10 m²

lori ipsum 1 dormitórios kietjiojwoijdej 16, 31 e 107 m²

Desired output is:

[0] => 1, [1] => 2, [2] => 3

[0] => 2, [1] => 3

[0] => 3

[0] => 1

I try the follow regex:

(\d(?= dorms))|(\d(?= dormitórios))

My problem is with comma, spaces and "e" character, i dont what that in the result...

My test : regextest

Upvotes: 0

Views: 44

Answers (1)

The fourth bird
The fourth bird

Reputation: 163207

With your current regex (\d(?= dorms))|(\d(?= dormitórios)) you match only the 3 in 3 dormitórios and the 1 in 1 dormitórios because in your lookahead you specify a single whitespace followed by either dorms or | dormitórios.

You don't match the 3 in 3 dorm because you use (?= dorms) with an extra s.

Instead you could use 1 positive lookahead instead of 2 with an optional non capturing group (?:itórios)? to match both variants and add a word boundary \b before and after the word you want to match.

\d(?=.*?\bdorm(?:itórios)?\b)

Details

  • \d Match a single digit
  • (?= Non capturing group
    • .*? Match any character zero or more times non greedy
    • \b Word boundary
    • dorm(?:itórios)? Match dorm or dormitórios
    • \b Word boundary
  • ) Close non capturing group

Upvotes: 2

Related Questions