How to use python regex to get the first occurrence of a substring
While all the methods are relatively fast for small strings, the performance difference becomes more pronounced with larger strings or complex operations (regular expressions or manual looping). partition() remains one of the fastest, as it is optimized for splitting based on a delimiter.
Solution using partition():
test_string = "I have three symbol but I want the first occurrence of symbol instead of the symbol in the middle and end"
before, word, after = test_string.partition("symbol")
print(f"Text before: {before}")
print(f"Text after: {after}")
Solution using re.search():
import re
test_string = "I have three symbol but I want the first occurrence of symbol instead of the symbol in the middle and end"
regex = "(.*?)symbol(.*)"
match = re.search(regex, test_string)
if match:
before = match.group(1) # Text before the first "symbol"
after = match.group(2) # Text after the first "symbol"
print(f"Before the first 'symbol': {before}")
print(f"After the first 'symbol': {after}")
else:
print("No match found.")
Solution using find():
test_string = "I have three symbol but I want the first occurrence of symbol instead of the symbol in the middle and end"
index = test_string.find("symbol")
if index != -1:
print(f"Text before: {test_string[:index]}")
print(f"Text after: {test_string[index + len('symbol'):]}")
Solution using split():
test_string = "I have three symbol but I want the first occurrence of symbol instead of the symbol in the middle and end"
before, after = test_string.split("symbol", 1)
print(f"Text before: {before}")
print(f"Text after: {after}")
Solution using index():
test_string = "I have three symbol but I want the first occurrence of symbol instead of the symbol in the middle and end"
index = test_string.index("symbol")
before = test_string[:index]
after = test_string[index + len("symbol"):]
print(f"Text before: {before}")
print(f"Text after: {after}")
Read more here: Source link
