Heisenberg
Heisenberg

Reputation: 79

Finding longest numeric subsequence inside a string

I have a string like: "Aggecvehtafv12357748615ahfwgbej134" I want to find the longest numeric subsequence inside that string in python. Answer to this I want is: "12357748615"

Upvotes: 1

Views: 223

Answers (2)

Sonia Samipillai
Sonia Samipillai

Reputation: 620

Try this one.

def longest_number(input_string):
  '''
  input
  -----
  Provide the string

  Notes
  -----
  Takes the input string and returns the longest sequence of number inside 
  the string

  '''

  import re
  x = re.findall("\d+", input_string)
  len_ = [len(seq) for seq in x]
  idx = np.argmax(len_)
  return x[idx]

Upvotes: 1

Thierry Lathuille
Thierry Lathuille

Reputation: 24282

Short solution: use re.findall to find the sequences of digits, and get the longest by using len as the key for max:

import re

s = 'Aggecvehtafv12357748615ahfwgbej134'

print(max(re.findall(r'\d+', s), key=len))
# '12357748615'

Upvotes: 4

Related Questions