【问题标题】:Finding numbers within certain string in Python [duplicate]在Python中查找特定字符串中的数字[重复]
【发布时间】:2020-09-09 20:15:11
【问题描述】:

我开始学习 Python,现在才开始学习正则表达式。我想弄清楚搜索字符串以找到始终直接跟随某个子字符串的数字(可以是不同长度)的最佳方法是什么。

例如:

string = """ this is a very long string with 495834 other numbers;
             if I had the ( 5439583409 );
             Keyword_indicator( 53029453 ); //
             energy to type more and more; ..."""

我希望能够在字符串中搜索仅显示在此处的“Keyword_indicator”,然后在括号内拉出数字,知道该数字不是设定的长度。

output = "53029453"

编辑 - 字符串中包含其他数字,而我要查找的数字始终是整数。

【问题讨论】:

标签: python regex


【解决方案1】:
import re
string = """ this is a very;
             long string if I had the;
             Keyword_indicator( 53029453 ); //
             energy to type more and more; ..."""
m = re.search('Keyword_indicator.*?(\d+)', string)
output = m.group(1)

【讨论】:

  • 赞成提供正则表达式解决方案。
  • 我想这就是我要找的东西,谢谢你的帮助。
  • 您可能希望稍微收紧一点,因为它与 Keyword_indicators are needed, call me at 53029453 ) 中的数字匹配
【解决方案2】:

在你的情况下,你可以使用:

import re
string = """ this is a very long string with 495834 other numbers;
             if I had the ( 5439583409 );
             Keyword_indicator( 53029453 ); //
             energy to type more and more; ..."""

#This would also match 5439583409 from bla5439583409bla.
re.findall(r'\d+', string)
result will be:
['495834', '5439583409', '53029453']

#If you only want numbers delimited by word boundaries (space, period, comma), you can use \b :
re.findall(r'\b\d+\b', string)
result will be:
['495834', '5439583409', '53029453']

#list of numbers instead of a list of strings:
[int(s) for s in re.findall(r'\b\d+\b', string)]

【讨论】:

    【解决方案3】:

    这是一种方法:

    string = 'biu89'
    numbers = ''
    for l in string:
        try: numbers+=str(int(l))
        except: pass
    print(numbers)
    

    输出:

    89
    

    注意:所有数字都将连接为一个。

    【讨论】:

      【解决方案4】:

      可以尝试类似以下的方法:

      >>> import re #import rejex
      >>> just='Standard Price:20000' #provide a string
      >>> re.search(r'\d+',just).group() #searches string for a digit values and groups
      '20000' #result
      

      所以它的效果是:

      string = """ this is a very;
                   long string if I had the;
                   Keyword_indicator( 53029453 ); //
                   energy to type more and more; ...""" #OP provided string
      print(re.search(r'\d+', string).group()) #search for digit values in OP provided string, group, and output the result. 
      

      【讨论】:

      • 代码不是很清楚。
      猜你喜欢
      • 2018-11-30
      • 2017-09-25
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 2021-11-05
      • 1970-01-01
      • 2015-08-06
      相关资源
      最近更新 更多