Complex regex

I want to capture a substring of a string, choosing the number of characters, but if any word is cut, then until the last space is received.

As an example, if this is text:

"This is an example of lorem ipsum text, etc."

12 characters would give "This is e." In this case, the last word is cut, so the result should be "This."

Is it possible to do this with regular expressions?

+3
source share
2 answers
^.{0,11}\w\b

Here, 12 characters will be found, where the last character of the word \w, followed by the word break \b. A word break is a zero-length statement that matches the beginning or end of a word.

: \w\b , , .

+6

@JohnKugelman's:

^([\w\s]{0,12})\s

, ( 12 ). :

^([\w\s]{1,12})\b

, (, ..).

( )

+1

Source: https://habr.com/ru/post/1785534/


All Articles