I have a Python script with a regex pattern that searches for the word employee_id if there is an equals sign immediately before or after.
import re
pattern = r"(=employee_id|employee_id=)"
print(re.search(pattern, "=employee_id").group(1)) # =employee_id
print(re.search(pattern, "employee_id=").group(1)) # employee_id=
print(re.search(pattern, "=employee_id=").group(1)) # =employee_id
print(re.search(pattern, "employee_id")) # None
print(re.search(pattern, "employee_identity=")) # None
How can I modify my regex pattern to only capture the employee_id part of the string without the equals sign?
# Desired results
print(re.search(pattern, "=employee_id").group(1)) # employee_id
print(re.search(pattern, "employee_id=").group(1)) # employee_id
print(re.search(pattern, "=employee_id=").group(1)) # employee_id
print(re.search(pattern, "employee_id")) # None
print(re.search(pattern, "employee_identity=")) # None
I attempted to use capture groups, but putting parentheses around employee_id meant my results were split between two capture groups:
pattern = r"=(employee_id)|(employee_id)="
print(re.search(pattern, "employee_id=").group(1)) # None
print(re.search(pattern, "employee_id=").group(2)) # employee_id
Using optional groups would match an employee_id without any equals sign.
(?:=)?(employee_id)(?:=)?
I also do not want to exclude matches where the character is both before and after the word.
Try:
Regex demo.
Or if you want it matched inside a capture group
Regex demo.
This matches
employee_idif there is=before or after the stringEDIT: Python example:
Prints:
OR: You can add capturing group around the pattern:
You can put capturing group around the pattern:
Prints: