-1

I need to extract a word following a keyword only if the word is < 20 characters long...

my_regex = re.compile(r'(keyword)\s*(\S{0,20}$))

for example:

keyword anbc123

will extract keyword and anbc123.

however below should not give any result

keyword anbc123nmnmnmnmnmnmnmnmnmnmn

this works...

But, below should work too since word following keyword is less than 20 characters long..how do I fix the regex ? I understand $ is for end of string....

keyword abnc 1234

expected result: keyword abnc

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397

1 Answers1

-1

You can use \b in place of $, \b matches a "word boundary", meaning the beginning or end of a word. In this case it will match the end of the word or end of the string

(keyword)\s*(\S{0,20})\b
Iain Shelvington
  • 18,267
  • 22
  • 35