0

Problem summary

I have this regex python code:

In

lst =[' ', 'US$170.8980\xa0billion', '[2]', '\xa0(2018)']
for i in lst:
    pat = re.compile(r'([\x1F-\x7F]+).+(\d+)')
    results=pat.search(i)
    print(results)

I am getting this ouput with my regex pattern:

Out

None
<_sre.SRE_Match object; span=(0, 11), match='US$170.8980'>
None
<_sre.SRE_Match object; span=(1, 6), match='(2018'>

Desired Ouput

Ideally, I want to get this output:

[US$170.8980-billion-(2018)]
3
  • The parentheses in your regular expression are for capturing groups, if you want to match a literal ( you need to escape it `(' Commented Aug 4, 2019 at 18:56
  • 1
    What do you want, a better pattern or a different way to do it ? It looks like both because you're inputting a list into a regex black box and coming out with a single string with hyphens.. Commented Aug 4, 2019 at 19:12
  • A different way to do it. Until all desired information exists I don't care for hyphens or formatting. Commented Aug 4, 2019 at 19:17

2 Answers 2

1

This works for me:

string = 'US$170.8980\xa0billion'
pat = ''.join(re.findall('([a-zA-Z0-9$.])', string))

Adapted

lst = [' ', 'US$170.8980\xa0billion', '[2]', '\xa0(2018)']
for i in lst:
    pat = ''.join(re.findall('([a-zA-Z0-9$.\s])', i))
    print(pat)

Alternative:

(re.findall('([^�])', i)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot but it still contains unwanted reference '[2]'
1

Maybe, this expression might be close to what you have in mind,

import re

lst =[' ', 'US$170.8980\xa0billion', '[2]', '\xa0(2018)']

output =''
for index,item in enumerate(lst):
    item = item.strip()
    if re.match('\[\d+\]',item) == None:
        if index == len(lst)-1:
            output +='-'
        output += re.sub(r'[^ -~]','-', item)

print(output)

not sure though.

Output

US$170.8980-billion-(2018)

1 Comment

Thanks for your suggestion. Actually, I will use this code in scrapy xpath. I am not sure I can fit your suggested code there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.