使用Python re.match提取字符串

run*_*ode 22 python regex python-2.7

import re
str="x8f8dL:s://www.qqq.zzz/iziv8ds8f8.dafidsao.dsfsi"

str2=re.match("[a-zA-Z]*//([a-zA-Z]*)",str)
print str2.group()

current result=> error
expected => wwwqqqzzz
Run Code Online (Sandbox Code Playgroud)

我想提取字符串wwwqqqzzz.我怎么做的?

也许有很多点,例如:

"whatever..s#$@.d.:af//wwww.xxx.yn.zsdfsd.asfds.f.ds.fsd.whatever/123.dfiid"
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我基本上想要的东西是///.我如何实现这一目标?

另外一个问题:

import re
str="xxx.yyy.xxx:80"

m = re.search(r"([^:]*)", str)
str2=m.group(0)
print str2
str2=m.group(1)
print str2
Run Code Online (Sandbox Code Playgroud)

似乎m.group(0)并且m.group(1)是相同的.

Mar*_*der 38

match尝试匹配整个字符串.请search改用.以下模式将符合您的要求:

m = re.search(r"//([^/]*)", str)
print m.group(1)
Run Code Online (Sandbox Code Playgroud)

基本上,我们正在寻找/,然后消耗尽可能多的非斜线字符.这些非斜线字符将在第1组中捕获.

事实上,有一种稍微先进的技术可以做同样的事情,但不需要捕获(这通常很耗时).它使用了所谓的lookbehind:

m = re.search(r"(?<=//)[^/]*", str)
print m.group()
Run Code Online (Sandbox Code Playgroud)

Lookarounds不包含在实际匹配中,因此是期望的结果.

这个(或任何其他合理的正则表达式解决方案)不会.立即删除s.但这可以在第二步轻松完成:

m = re.search(r"(?<=//)[^/]*", str)
host = m.group()
cleanedHost = host.replace(".", "")
Run Code Online (Sandbox Code Playgroud)

这甚至不需要正则表达式.

当然,如果你想删除除字母和数字之外的所有内容(例如www.regular-expressions.info转入wwwregularexpressionsinfo),那么你最好使用正则表达式版本replace:

cleanedHost = re.sub(r"[^a-zA-Z0-9]+", "", host)
Run Code Online (Sandbox Code Playgroud)