Reputation: 351
I would like to match any four digits occurring before double space and word "from" ex.
2356 from
1524 from
1223 from
The expression \d{4} from
extracts digits, double space and the word "from", but ideally I would like to get only those four digits (without the trailing spaces and word "from") and only in cases when they are not part of number with hyphen like this example:
2536 from
= 2536
8574 from
= 8574
35-6655 from
= no match3652
= no match (number without word "from" after the digits)Upvotes: 1
Views: 124
Reputation: 8695
You need to use either grouping (...)
operators in your regex:
(\d{4}) from
and then extract group #1 from the match. Or a zero-width look-ahead match using (?=...)
.
\d{4}(?= from)
To avoiding a match following the hyphen, you can use a zero-width negative look-behind.
(?<!-)\d{4}(?= from)
Explanation:
(?<!_)_______________
negative zero-width look-behind ...
____-________________
... doesn't match if a "-"
is found
______\d{4}__________
four digits
___________(?=______)
positive zero-width look-ahead ...
______________ from_
... matches if " from"
is found
Upvotes: 2