数据提取之正则表达式

9 篇文章 0 订阅
7 篇文章 0 订阅

 

 

  • re.match(从头找一个)
  • re.search(找一个)
  • re.findall(找所有)
    • 返回一个列表,没有就是空列表
    • re.findall("\d","chuan1zhi2") >> ["1","2"]
  • re.sub(替换)

    • re.sub("\d","_","chuan1zhi2") >> ["chuan_zhi_"]
  • re.compile(编译,提升匹配速度)

    • 返回一个模型P,具有和re一样的方法,但是传递的参数不同
    • 匹配模式需要传到compile中

      p = re.compile("\d",re.S)
      p.findall("chuan1zhi2")

假设现在想把字符串 title = u'你好,hello,世界' 中的中文提取出来,可以这么做:

import re

title = u'你好,hello,世界'
pattern = re.compile(ur'[\u4e00-\u9fa5]+')
result = pattern.findall(title)

print result

# 注意点: 中文匹配 需要设置unicode字符才可以匹配

 

  • 如何非贪婪的去匹配内容?
import re

s = '123xxxxxx456'

result_1 = re.findall('\d+', s)
result_2 = re.findall('\d+?', s)

print(result_1)
print(result_2)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Java中,可以使用正则表达式提取数据。具体的步骤如下: 1. 创建一个 Pattern 对象,该对象表示需要匹配的正则表达式。 2. 使用 Pattern 对象的 matcher 方法,创建一个 Matcher 对象,该对象表示需要匹配的字符串。 3. 使用 Matcher 对象的 find 方法,查找匹配的字符串。 4. 使用 Matcher 对象的 group 方法,获取匹配到的字符串。 下面是一个简单的示例代码,演示了如何使用正则表达式提取一个字符串中的数字: ```java import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexDemo { public static void main(String[] args) { String input = "Hello 123 World"; Pattern pattern = Pattern.compile("\\d+"); Matcher matcher = pattern.matcher(input); if (matcher.find()) { String match = matcher.group(); System.out.println("Matched: " + match); } else { System.out.println("No match found."); } } } ``` 在上面的代码中,我们使用了 `\d+` 这个正则表达式来匹配字符串中的数字。其中,`\d` 表示匹配数字,`+` 表示匹配一个或多个数字。我们使用了 Pattern.compile 方法来创建一个 Pattern 对象,然后使用该对象的 matcher 方法来创建一个 Matcher 对象。接着,我们使用 Matcher 对象的 find 方法来查找匹配的字符串,如果找到了就使用 group 方法获取匹配到的字符串。最后,我们输出了匹配到的字符串。 执行上面的代码,输出结果如下: ``` Matched: 123 ``` 可以看到,我们成功地使用正则表达式提取了字符串中的数字。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

毛毛虫会长大

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值