用于在括号内打印整数的正则表达式 [英] Regular expression for printing integers within brackets

查看:30
本文介绍了用于在括号内打印整数的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次使用正则表达式,尽管在 stackoverflow 中已经有很多示例,但无法使其正常工作.

First time ever using regular expressions and can't get it working although there's quite a few examples in stackoverflow already.

如何提取括号内字符串中的整数?

How can I extract integers which are in a string inside bracket?

示例:

dijdi[d43]     d5[55++][ 43]  [+32]dm dij [    -99]x

会回来

[43, 32, -99]

'+''-' 是可以的,如果它在括号的开头,但如果它在中间或结尾就不行.如果 '+' 符号在开头,则不应考虑.(+54 --> 54)

'+' and '-' is okay, if it's in the beginning of the brackets, but not okay if it's in the middle or end. If the '+' sign is in the beginning, it should not be taken into account. (+54 --> 54)

一直在尝试:

re.findall('\[[-]?\d+\]',str)

但它没有按照我想要的方式工作.

but it's not working the way I want.

推荐答案

如果你需要在 [ +-34 ] 中的匹配失败(即如果你不需要提取负数,如果有在它之前是 +)你需要使用

If you need to fail the match in [ +-34 ] (i.e. if you needn't extract a negative number if there is a + before it) you will need to use

\[\s*(?:\+|(-))?(\d+)\s*]

并且在获得匹配时,连接第 1 组和第 2 组值.请参阅此正则表达式演示.

and when getting a match, concat the Group 1 and Group 2 values. See this regex demo.

详情

  • \[ - 一个 [ 字符
  • \s* - 0+ 个空格
  • \+? - 一个可选的 + 字符
  • (-?\d+) - 捕获组 1(re.findall 的实际输出):可选的 - 和 1+数字
  • \s* - 0+ 个空格
  • ] - 一个 ] 字符.
  • \[ - a [ char
  • \s* - 0+ whitespaces
  • \+? - an optional + char
  • (-?\d+) - Capturing group 1 (the actual output of re.findall): an optional - and 1+ digits
  • \s* - 0+ whitespaces
  • ] - a ] char.

在 Python 中,

In Python,

import re
text = "dijdi[d43]     d5[55++][ 43]  [+32]dm dij [    -99]x"
numbers_text = [f"{x}{y}" for x, y in re.findall(r'\[\s*(?:\+|(-))?(\d+)\s*]', text)]
numbers = list(map(int, numbers_text))

# => [43, 32, -99] for both

这篇关于用于在括号内打印整数的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆