FotoDJ
FotoDJ

Reputation: 351

Regex to match exact phrase before certain word

I would like to match any four digits occurring before double space and word "from" ex.

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:

Upvotes: 1

Views: 124

Answers (2)

AJNeufeld
AJNeufeld

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

seokgyu
seokgyu

Reputation: 147

You can do by ([0-9]{4}) from

More see in here

Upvotes: 0

Related Questions