Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex regular expression

Tags:

regex

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

As example if this is the text:

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

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

Its possible do this with Regular Expressions?

like image 902
Jose3d Avatar asked Mar 11 '26 00:03

Jose3d


1 Answers

^.{0,11}\w\b

This will find 12 characters where the last one is a word character \w followed by a word break \b. A word break is a zero-length assertion which matches either the beginning or end of a word.

Result: The \w\b ensures that the final character of the match is the last character of a word so you don't get a partial word.

like image 71
John Kugelman Avatar answered Mar 12 '26 16:03

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!