python - 使用正则表达式提取字符串

标签 python regex

我需要从以下字符串中提取 IP 地址。

>>> mydns='ec2-54-196-170-182.compute-1.amazonaws.com'

需要返回点左边的文本。以下按预期工作。

>>> mydns[:18]
'ec2-54-196-170-182'

但并不是在所有情况下都有效。例如

mydns='ec2-666-777-888-999.compute-1.amazonaws.com'

>>> mydns[:18]
'ec2-666-777-888-99'

如何在 python 中使用正则表达式?

最佳答案

不需要正则表达式...只需使用 str.split

mydns.split('.', 1)[0]

演示:

>>> mydns='ec2-666-777-888-999.compute-1.amazonaws.com'
>>> mydns.split('.', 1)[0]
'ec2-666-777-888-999'

关于python - 使用正则表达式提取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20626987/

相关文章:

Python面向对象编程: Automatically changing instances of a class after changing a class attribute?

html - 从字体到跨度(大小和颜色)和背面的正则表达式(VB.NET)

python - pandas left join - 为什么会有更多结果?

python - 支持不起作用

python - 为什么这个 xlsx 文件打不开?

python - 如何按字典中的值对字典列表进行排序?

regex - 如何查找具有所有指定字符且重复的单词?

javascript - 正则表达式剥离图像尺寸 125x125

c# - 点之间的数字子串

android - 如何 swift 检查非法字符。 (适用于Windows,Android和IOS的非法字符)