Do you only have access to the built-in
With only
So there is code here, but it doesn't modify the search string at all, just calculates the pattern.
re
class for matching, or can you use other things like the regex
module?With only
re
matching, this seems difficult. The lookbehind stuff could be useful, but it has to be fixed length, so you can't have it be all matches. Can you get the length of the string before the match? If so, you could build the pattern based on that. Here's an example. I asked it to look for matches only in the first 12 characters. It correctly finds the word inside that limit, and does not find anything that is straddling or beyond the limit. It does this by forcing the match to find at least n characters afterward, where n is calculated so that the match must be in the required portion.So there is code here, but it doesn't modify the search string at all, just calculates the pattern.
import re source_text = "A long string that has no evidence of the word apple early in the string" match_before = 12 targets = ["long", "apple", "string"] for target in targets: print(f"Looking for {target}...", end="") ignore_portion = max(len(source_text) - match_before, 0) pattern = re.compile(fr"{target}.{{{ignore_portion},}}$") if re.search(pattern, source_text): print(" Found") else: print(" No match")
Output:Looking for long... Found
Looking for apple... No match
Looking for string... No match