I have a question for Python's regular show!

Asked 2 years ago, Updated 2 years ago, 34 views

You want to print out the rest of the words except when the text is input and the extension is txt or hwp, as shown below.

What should the regular expression be like? I'm asking this question after thinking about it for two days.

input : liveL.ppt, abcd.txt, img.pdf, chessrule.hwp
output: liveL.ppt, img.pdf

\b(?!\w+.(txt|hwp).*(?=\w+.(txt|hwp))\b I tried to organize a regular expression like this, but I couldn't find it as a whole, and I even printed out a comma. I sincerely ask for your help.

python regex

2022-09-20 22:08

1 Answers

Unless it's just a regular expression, you just have to approach it really simply.

input_string = "liveL.ppt, abcd.txt, img.pdf, chessrule.hwp"

# Convert text to file name unit list
input_list = input_string.split(", ")

# There's no .hwp on the list.I only pick ones that don't have a pdf
# If the file name is .hwp...pdf...txt, it will be a problem, but it will be a little later
output_list = filter(lambda x: '.hwp' not in x and '.pdf' not in x, input_list)

# process and use whatever one wants
output_string = ", ".join(output_list)
print(output_string)

Go further... If the text of those filenames is not text that the user enters in the form of a web page, it's actually just making the list of physical files in a directory easier to see... Wouldn't it be better to just do a conditional search of the files in that directory right there? In short, let's do what we really want to do in the most primitive way.

What do you really want to do? In some cases, there might be a more reasonable way than a regular expression.


2022-09-20 22:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.