Home > OS >  Regex ignore last withe space
Regex ignore last withe space

Time:09-21

I have this regex:

enter image description here

from which I get all the sentence except the last word, but I have problems if this word has a space at the end. example: enter image description here

CodePudding user response:

You can use this pattern: \S \b

See Regex Demo

Explanation

  • \S one or more from all non-whitespace characters.
  • an empty space.
  • \b word boundary. a position between words character (\w) and non words character (\W)

CodePudding user response:

Try this regex. Made sure last white space is ignored

(^.*)[!<=\S]

Following regex can be used to ignore all whitespaces

\S*

CodePudding user response:

You could use a positive lookahead asserting 1 or more spaces without newlines followed by a non whitespace char to the right:

^. (?=[^\S\r\n] \S)

Regex demo

If you also want to match a single word at the start of the string, you can add an alternation | and match only 1 or more nonwhiteapace chars:

^(?:. (?=[^\S\r\n] \S)|\S )

Regex demo

Another option could be using a capture group, with an optional part matching non whotespace chars between spaces:

^(. ?)(?:  \S  *)?$

Regex demo

  • Related