首页 > 解决方案 > How to extract a leading number from a string?

问题描述

I have a couple of string and I want to split them based on the numbers in it.

Ex:

  1. 5Hello
  2. 10HelloWorld
  3. 16HelloWorldPython

In all these cases I want to extract the numbers that is 5, 10 and 16. The numbers could be up to infinity.

This is because I want to extract numbers and compare the length of the string whether they are equal or not.

标签: pythonregex

解决方案


>>> import re
>>> re.findall(r'\d+', '5Hello')
[5]  
>>> re.findall(r'\d+', '10HelloWorld')
[10]

Edit : Answer to the specific question

import re

def check_len(x):
  match = re.search(r'(\d+)(\w+)', x)
  return int(match[1])==len(match[2])

check_len('5hello')
True 

check_len('4rabbits')
False

推荐阅读