Python (re)

Twitter / X URL in PY

Match Twitter/X profile and status URLs, capturing the handle and (optional) tweet ID.

Try it in the PY tester →

Pattern

regexPY
https?:\/\/(?:www\.)?(?:twitter|x)\.com\/([A-Za-z0-9_]{1,15})(?:\/status\/(\d+))?   (flags: g)

Python (re) code

pyPython
import re

pattern = re.compile(r"https?:\/\/(?:www\.)?(?:twitter|x)\.com\/([A-Za-z0-9_]{1,15})(?:\/status\/(\d+))?")
input_text = "https://twitter.com/jack/status/20"
for m in pattern.finditer(input_text):
    print(m.group(0))

Stdlib `re` module — no third-party dependency. Works on Python 3.6+.

How the pattern works

https?:\/\/(?:www\.)?(?:twitter|x)\.com matches the domain — both legacy twitter.com and current x.com, with optional www. ([A-Za-z0-9_]{1,15}) captures the handle. (?:\/status\/(\d+))? optionally captures a tweet ID for status URLs.

Examples

Input

https://twitter.com/jack/status/20

Matches

  • https://twitter.com/jack/status/20

Input

Profile: https://x.com/elonmusk

Matches

  • https://x.com/elonmusk

Input

no twitter links

No match

Same pattern, other engines

← Back to Twitter / X URL overview (all engines)