ftft32
ftft32

Reputation: 19

regular expression match everything after the last space with the word of max 2 or 5 characters

First it need to match the last space of the string

"this is a test NL" with the code (.*\s) i get the word NL

"this is a test NL-NL" with the code (.*\s) i get the word NL-NL

But

"this is a test NL Search" with the code (.*\s) i get the word Search this is wrong. It should return nothing

The last word my have 2 or 5(with special char - or /) character. This is de code but it's not working

(.*\s)(\w{2}|\w-/{5})

Upvotes: 0

Views: 222

Answers (2)

Per Huss
Per Huss

Reputation: 5105

You are probably looking for something like (?<=\s)(\w{2}|[\/\-\w]{5})$

Where the different parts means:

  • (?<=\s) Positive lookbehind should be a space (start match after)
  • (...|...) Either ... or ...
  • \w{2} Any two word characters
  • [\/\-\w]{5} Slash, hyphen or any word character (five times)
  • $ End of line

You can test the expression here.

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163517

You might use a capturing group if you want to capture the value (or make it non capturing (?:) with a character class and an alternation using | to match either 2 word chars or match 5 times one of the listed.

^.*\s(\w{2}|[\w/-]{5})$

Regex demo

Note that \s could also match a newline.


If the / and - can not occur 2 times after each other, not at the start or end and there must be at least 1 occurrence of them:

^.*\s(\w{2}|(?=[\w/-]{5}$)\w+(?:[/-]\w+)+)$

Regex demo


Or make the second part of the string optional

^.*\s([a-zA-Z]{2}(?:[/-][a-zA-Z]{2})?)$

Regex demo

Upvotes: 1

Related Questions