Regular expression: matching words between spaces

I'm trying to do something pretty simple with regex in python ... here is what I was thinking at least.

What I want to do is match words from a string, if it precedes and is followed by a space. If there is no space at the beginning of the line required earlier - if it is at the end, do not look for spaces.

Example:

"WordA WordB WordC-WordD WordE"

I want to combine WordA WordB WordE.

I just came up with a tricky way to do this ...

(?<=(?<=^)|(?<=\s))\w+(?=(?=\s)|(?=$))

It seems to me that for such a simple problem there should be an easy way ... I decided that I can start with (?<=\s|^), but this does not seem possible, because "look-behind requires a fixed-width template".

+6
1

, , Python, (?<=^|\s) PCRE, Java Ruby ( .NET regex lookbehind ).

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

1 , / .

regex.

:

  • (?<!\S) - lookbehind, , -whitespace char
  • \w+ - 1
  • (?!\S) - , , -whitespace char .
+6

All Articles