How to find a regex pattern after a specific number of characters?

Member

by gilbert , in category: Third Party Scripts , a month ago

How to find a regex pattern after a specific number of characters?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , a month ago

@gilbert 

To find a regex pattern after a specific number of characters, you can use the positive lookbehind assertion in regex. Here is an example of how you can do this in Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import re

text = "This is a sample text with pattern after 5 characters:pattern"

pattern = re.compile(r'(?<=.{5})pattern')

matches = pattern.findall(text)

for match in matches:
    print(match)


In this example, the regex pattern (?<=.{5})pattern will find the word "pattern" that occurs after 5 characters in the string. The .{5} matches any 5 characters, and the positive lookbehind (?<=) asserts that the pattern "pattern" should come after these 5 characters.