satya
satya

Reputation: 84

Find value using python regex in a string

In this example I need salt value in both strings.

string = 'SHA-224(Salt len: 20)'

string2 = '# Salt len: 0' 
 
pattern = re.compile(r'^(#\s)?((SHA-\d+)?\(?Salt len: \d+\)?)') 
 
result = pattern.search(string)  

result2 = pattern.search(string2)

print(result)

print(result2)   

Expected output:
20
0

please help me guys

Upvotes: 1

Views: 316

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You may use a simpler pattern that will match Salt len:, spaces and then captures any amount of digits:

pattern = re.compile(r'\bSalt len: (\d+)')

See the regex demo.

Details

  • \b - a word boundary
  • Salt len: - a string
  • (\d+) - Capturing group 1: one or more digits

When using in Python, check for a match first:

result = pattern.search(string)

Then, check if there was a match, and if yes, extract Group 1 value.

Python demo:

import re
texts = ['SHA-224(Salt len: 20)', '# Salt len: 0']
pattern = re.compile(r'\bSalt len: (\d+)') 
for text in texts:
    result = pattern.search(text)
    if result:
        print(result.group(1))

Upvotes: 1

Related Questions