Regex words in lowercase

Asked

Viewed 110 times

0

I have a Regex that removes characters that are not letters or space for a Python application. Ex:

var = re.sub('[^a-zA-Z \\\]', '', "abc Abc aBC cde123 def-ghi $?!123")

Is returning:

abc Abc aBC cde defghi

I need that, besides that, also return everything in tiny:

abc abc abc cde defghi
  • 1

    Could [Edit] the question, adding examples of strings and how should the output be? For me it is not very clear what should be returned. Ex: if I have strs = "abc Abc aBC cde123 def-ghi", what would be the lower case words? I understood that abc Yeah, 'cause it’s all tiny, Abc no, because it starts with A, but aBC starts with lowercase, she tells? cde123 has lowercase letters but tb has numbers, so it doesn’t fit, right? And def-ghi is a single word (since this is possible in English, for example), or would be 2 words (def and ghi)?

  • 1

    Hello @hkotsubo I already edited the question, I think it is now clearer my need. Thank you

  • 1

    The method str.lower wouldn’t be enough for your case? Something like var.lower() would already return what, apparently, you want.

1 answer

2


Regex does not modify the text, it just identifies the text. In this case you are identifying the text and replacing it with empty, keeping the original text box. As the text has already been found just call lower() in the string returned.

var = re.sub('[^a-zA-Z \\\]', '', "string").lower()
  • It worked now. Thank you!

  • 1

    Regex does modify the text: just use the substitute, default of any language that supports regex. Example of substitution https://regex101.com/r/JzIETu/1

  • With re.sub would-be to do, if Python had token support \L, that turns references into lowercase (see an example - I had to change the regex a little to get the characters I want to change to lower case). And in this specific case, call lower() really is the simplest solution, but only for registration, it is possible to pass a function to sub, which in turn turns the character to lowercase: https://ideone.com/3bjnUL (again, your solution is simpler, my comment was just to complement even)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.