วิธีนำเข้า Regular Expression ใน Python

ในบทช่วยสอน Python RegEx (Regular Expression) นี้ คุณจะได้เรียนรู้วิธีนำเข้า Regular Expression ใน Python และใช้งาน การใช้โมดูลกับวิธีการทำงานกับ Regular Expression ใน Python

ภาษาการเขียนโปรแกรมเกือบทั้งหมดรองรับการแสดงออกปกติ Regex สร้างขึ้นในภาษาต่างๆ เช่น JavaScript และ Pearl ในขณะที่ภาษาอื่นๆ เช่น Java และ Python มีไลบรารี่มาตรฐานสำหรับการทำงานกับมัน

ในบทความนี้ เราจะมาดูกันว่าคุณสามารถนำเข้านิพจน์ทั่วไปใน Python และใช้งานได้อย่างไร เราจะดูวิธีการบางอย่างที่ Python เตรียมไว้สำหรับการทำงานกับนิพจน์ทั่วไป

สารบัญ:

  • วิธีนำเข้า Regular Expression ใน Python
  • วิธีใช้reโมดูล Python กับ RegEx
    • ตัวอย่าง RegEx ด้วยmatch()วิธีการ
    • ตัวอย่าง RegEx ด้วยsearch()วิธีการ
    • ตัวอย่าง RegEx ด้วยfindall()วิธีการ
    • ตัวอย่าง RegEx ด้วยsplit()วิธีการ
    • ตัวอย่าง RegEx ด้วยsub()วิธีการ
  • บทสรุป

วิธีนำเข้า Regular Expression ใน Python

Python จัดเตรียมreโมดูลสำหรับการใช้นิพจน์ทั่วไป เป็นโมดูลมาตรฐานที่สร้างขึ้นใน Python ดังนั้นหากคุณมี Python เวอร์ชันล่าสุด คุณไม่จำเป็นต้องติดตั้งแยกต่างหากกับตัวจัดการแพ็คเกจ

ในการนำเข้าreโมดูลใน Python ให้ทำโดยใช้คำสำคัญนำเข้า:

import re

วิธีใช้reโมดูล Python กับ RegEx

Python มีเมธอดบางอย่างที่คุณสามารถใช้เพื่อทำงานกับนิพจน์ทั่วไป เช่นmatch(), search(), findall(), split(), sub()และ

หากต้องการใช้วิธีการเหล่านั้นกับ RegEx คุณต้องต่อท้ายด้วยreโมดูลและจุด ( .) ดังนี้:

re.match(pattern, string) # to use the match method
re.findall(pattern, string) # to use the findall method 
re.sub(pattern, string) # to use the sub method
re.search(pattern, string) # to use the search method 
re.split(pattern, string) # to use the split method

ตัวอย่าง RegEx ที่ฉันให้ไว้จะใช้วิธีการเหล่านั้น

ตัวอย่าง RegEx โดยใช้match()วิธี

ใช้match()นิพจน์ทั่วไปและสตริง จากนั้นตรวจสอบว่าสตริงตรงกับรูปแบบในนิพจน์ทั่วไปหรือไม่

นี่คือตัวอย่าง:

import re 

my_txt = 'freeCodeCamp'
my_regex_1 = '^freecodecamp$'

res = re.match(my_regex_1, my_txt)
print(res) # returns None

ในตัวอย่างด้านบน:

  • ฉันมีmy_txtชุดตัวแปรเป็นfreeCodeCampและmy_regex_1ชุดตัวแปรเป็นรูป^freecodecamp$แบบ นั่นคือวิธีที่คุณเขียน Regular Expression ใน Python โดยใส่ไว้ในเครื่องหมายคำพูด
  • ในการตรวจสอบว่าข้อความตรงกับรูปแบบหรือไม่ ผมใช้match()วิธีใส่ตัวแปรmy_regex_1และmy_txt

สตริงคือfreeCodeCampและรูปแบบคือ เหตุ ใด^freecodecamp$เมธอดการจับคู่จึงกลับมา Noneเพราะมันหาคู่ไม่เจอ

มีตัวพิมพ์ใหญ่บางตัวในmy_txtตัวแปร แต่รูปแบบกำลังมองหาตัวพิมพ์เล็ก

หากคุณคุ้นเคยกับ RegEx ใน JavaScript หรือ Pearl คุณสามารถใช้iแฟล็กเพื่อจับคู่ตัวอักษรตัวพิมพ์ใหญ่หรือตัวพิมพ์เล็กทั้งหมดในสตริง

ดังนั้นสิ่งที่เราต้องทำเพื่อการแข่งขันคือการใช้iธง แต่การใช้แฟล็กที่มีนิพจน์ทั่วไปใน Python นั้นแตกต่างจากที่เราใช้ใน JavaScript

หากต้องการใช้แฟล็กกับนิพจน์ทั่วไปใน Python reโมดูลจะจัดเตรียมตัวเลือกIGNORECASE, ASCII, MULTILINE, VERBOSE, DOTALL, และLOCAL

นี่คือวิธีที่คุณจะใช้แฟล็กกับนิพจน์ทั่วไปใน Python:

re.match(pattern, string, re.ASCII) # to perform only ASCII matching 
re.findall(pattern, string, re.DOTALL) # to match any character – including a new line.
re.sub(pattern, string, re.IGNORECASE) # to perform case insensitive matching
re.search(pattern, string, re.LOCALE) # to perform case insensitive matching dependent on the current locale
re.search(pattern, string, re.VERBOSE) # to allow comments in regex
re.split(pattern, string, re.MULTILINE) # to perform multiple line matching. Commonly used with metacharacters (^ and $)

สำหรับตัวอย่างของเรา แฟล็กที่เราสามารถใช้ได้คือIGNORECASE. ลองใช้มันเพื่อเราจะได้จับคู่กัน:

import re 

my_txt = 'freeCodeCamp'
my_regex_1 = '^freecodecamp$'

res = re.match(my_regex_1, my_txt, re.IGNORECASE)
print(res) #Output: <re.Match object; span=(0, 12), match='freeCodeCamp'>

ตอนนี้เรามีการแข่งขัน!

ตัวอย่าง RegEx โดยใช้search()วิธี

ฟังก์ชันsearch()ใช้ regex และสตริง จากนั้นส่งคืนเหตุการณ์แรกในออบเจกต์ที่ตรงกัน หากพบว่าไม่ตรงกัน ก็จะส่งNoneกลับ

import re 

my_txt = 'Every Friday, we have a standup meeting. The only reason why we might not have a meeting on a Friday is public holiday. That Friday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Friday.'

my_regex = 'friday'

res = re.search(my_regex, my_txt, re.IGNORECASE)
print(res) # <re.Match object; span=(6, 12), match='Friday'>

คุณจะเห็นว่ามันส่งกลับข้อความที่เกิดขึ้นครั้งแรกซึ่งFridayอยู่ระหว่างดัชนี6และ12

คุณสามารถรับดัชนีนั้นได้ด้วยstart()วิธีการ:

res = re.search(my_regex, my_txt, re.IGNORECASE)
print("The first occurrence is located at index ", res.start()) # The first occurrence is located at index  6

คุณสามารถรับดัชนีเริ่มต้นและสิ้นสุดของเหตุการณ์เช่นนี้:

res = re.search(my_regex, my_txt, re.IGNORECASE)
print("The first occurrence is located between index", res.start(), "and index", res.end()) # The first occurrence is located between index 6 and index 12

คุณยังสามารถใช้match()กับif…elseคำสั่ง:

import re 

my_txt = 'Every Friday, we have a standup meeting. The only reason why we might not have a meeting on a Friday is public holiday. That Friday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Friday.'

my_regex = 'friday'

if re.search(my_regex, my_txt, re.IGNORECASE):
    print("Found a match!") #Output: Found a match!
else:
    print("Found no match")   
res = re.search(my_regex, my_txt, re.IGNORECASE)

ตัวอย่าง RegEx โดยใช้findall()วิธี

เมธอดfindall()ใช้ regex และสตริง จากนั้นดูผ่านสตริงและค้นหาเหตุการณ์ทั้งหมดที่ตรงกับ regex มันทำให้เหตุการณ์เหล่านั้นทั้งหมดอยู่ในรายการ

นี่คือตัวอย่าง:

import re 

my_txt = 'Every Friday, we have a standup meeting. The only reason why we might not have a meeting on a Friday is public holiday. That Friday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Friday.'

my_regex = 'friday'
res = re.findall(my_regex, my_txt, re.IGNORECASE)

print(res) # Output: ['Friday', 'Friday', 'Friday', 'Friday']

โปรดสังเกตว่า regex ที่ฉันใช้มีข้อความfridayซึ่งไม่ตรงกับคำว่า “Friday” ธงIGNORECASEคือสิ่งที่ทำให้มันตรงกับเหตุการณ์เหล่านั้น

ตัวอย่าง RegEx โดยใช้split()วิธี

เมธอดsplit()ทำในสิ่งที่ชื่อบอกเป็นนัย - มันแยกสตริงตามรูปแบบที่ส่งผ่านเข้าไป

วิธีนี้อาจมีประโยชน์ถ้าคุณต้องการกรองคำบางคำที่คุณไม่ต้องการในสตริง

import re 

my_txt = "Python and JavaScript and C# and Java and Golang and F#"
my_regex = 'and'

res = re.split(my_regex, my_txt)
print(res) # ['Python ', ' JavaScript ', ' C# ', ' Java ', ' Golang ', ' F#']

ตัวอย่าง RegEx โดยใช้sub()วิธี

ทำงานsub()เหมือนreplace()วิธี ของจาวาสคริปต์ มันแทนที่อักขระที่ตรงกับนิพจน์ทั่วไปที่ส่งผ่านเข้าไป

วิธี นี้sub()แตกต่างจากวิธีอื่นเล็กน้อย – ใช้พารามิเตอร์สูงสุด 5 ตัว:

re.sub(pattern, replacement, string, count, flags)

ดังนั้น หากคุณต้องการระบุแฟล็กแต่คุณไม่ได้ระบุ แฟล็กcountจะไม่ทำงานตามที่คาดไว้

ไม่มีใครจัดการประชุมแบบสแตนด์อโลนในวันศุกร์ ดังนั้นลองใช้subวิธีการกับสตริงที่เราใช้สำหรับsearch()and findall()ตัวอย่าง:

import re 

my_txt = 'Every Friday, we have a standup meeting. The only reason why we might not have a meeting on a Friday is public holiday. That Friday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Friday.'

my_regex = 'friday'

res = re.sub(my_regex, "Monday", my_txt, 4, re.IGNORECASE)
print(res) # Output: Every Monday, we have a standup meeting. The only reason why we might not have a meeting on a Monday is public holiday. That Monday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Monday.

มี 4 เหตุการณ์Fridayในmy_txtสตริง นั่นเป็นเหตุผลที่ฉันระบุ 4 เป็นการนับ

บทสรุป

ในบทความนี้ เราดูวิธีการนำเข้านิพจน์ทั่วไปผ่านreโมดูล แต่เราไม่ได้หยุดอยู่แค่นั้น ฉันยังแนะนำวิธีการใช้โมดูลพร้อมวิธีการทำงานกับ Regular Expression ใน Python

นอกจากนี้ เรายังดูสั้นๆ เกี่ยวกับวิธีใช้แฟล็กในนิพจน์ทั่วไปของ Python

หากคุณพบว่าบทความนี้มีประโยชน์ อย่าลังเลที่จะแบ่งปันกับเพื่อนและครอบครัวของคุณ

ที่มา: https://www.freecodecamp.org

#python #regex

What is GEEK

Buddha Community

วิธีนำเข้า Regular Expression ใน Python
Shardul Bhatt

Shardul Bhatt

1626775355

Why use Python for Software Development

No programming language is pretty much as diverse as Python. It enables building cutting edge applications effortlessly. Developers are as yet investigating the full capability of end-to-end Python development services in various areas. 

By areas, we mean FinTech, HealthTech, InsureTech, Cybersecurity, and that's just the beginning. These are New Economy areas, and Python has the ability to serve every one of them. The vast majority of them require massive computational abilities. Python's code is dynamic and powerful - equipped for taking care of the heavy traffic and substantial algorithmic capacities. 

Programming advancement is multidimensional today. Endeavor programming requires an intelligent application with AI and ML capacities. Shopper based applications require information examination to convey a superior client experience. Netflix, Trello, and Amazon are genuine instances of such applications. Python assists with building them effortlessly. 

5 Reasons to Utilize Python for Programming Web Apps 

Python can do such numerous things that developers can't discover enough reasons to admire it. Python application development isn't restricted to web and enterprise applications. It is exceptionally adaptable and superb for a wide range of uses.

Robust frameworks 

Python is known for its tools and frameworks. There's a structure for everything. Django is helpful for building web applications, venture applications, logical applications, and mathematical processing. Flask is another web improvement framework with no conditions. 

Web2Py, CherryPy, and Falcon offer incredible capabilities to customize Python development services. A large portion of them are open-source frameworks that allow quick turn of events. 

Simple to read and compose 

Python has an improved sentence structure - one that is like the English language. New engineers for Python can undoubtedly understand where they stand in the development process. The simplicity of composing allows quick application building. 

The motivation behind building Python, as said by its maker Guido Van Rossum, was to empower even beginner engineers to comprehend the programming language. The simple coding likewise permits developers to roll out speedy improvements without getting confused by pointless subtleties. 

Utilized by the best 

Alright - Python isn't simply one more programming language. It should have something, which is the reason the business giants use it. Furthermore, that too for different purposes. Developers at Google use Python to assemble framework organization systems, parallel information pusher, code audit, testing and QA, and substantially more. Netflix utilizes Python web development services for its recommendation algorithm and media player. 

Massive community support 

Python has a steadily developing community that offers enormous help. From amateurs to specialists, there's everybody. There are a lot of instructional exercises, documentation, and guides accessible for Python web development solutions. 

Today, numerous universities start with Python, adding to the quantity of individuals in the community. Frequently, Python designers team up on various tasks and help each other with algorithmic, utilitarian, and application critical thinking. 

Progressive applications 

Python is the greatest supporter of data science, Machine Learning, and Artificial Intelligence at any enterprise software development company. Its utilization cases in cutting edge applications are the most compelling motivation for its prosperity. Python is the second most well known tool after R for data analytics.

The simplicity of getting sorted out, overseeing, and visualizing information through unique libraries makes it ideal for data based applications. TensorFlow for neural networks and OpenCV for computer vision are two of Python's most well known use cases for Machine learning applications.

Summary

Thinking about the advances in programming and innovation, Python is a YES for an assorted scope of utilizations. Game development, web application development services, GUI advancement, ML and AI improvement, Enterprise and customer applications - every one of them uses Python to its full potential. 

The disadvantages of Python web improvement arrangements are regularly disregarded by developers and organizations because of the advantages it gives. They focus on quality over speed and performance over blunders. That is the reason it's a good idea to utilize Python for building the applications of the future.

#python development services #python development company #python app development #python development #python in web development #python software development

Mad Libs: Using regular expressions

From Tiny Python Projects by Ken Youens-Clark

Everyone loves Mad Libs! And everyone loves Python. This article shows you how to have fun with both and learn some programming skills along the way.


Take 40% off Tiny Python Projects by entering fccclark into the discount code box at checkout at manning.com.


When I was a wee lad, we used to play at Mad Libs for hours and hours. This was before computers, mind you, before televisions or radio or even paper! No, scratch that, we had paper. Anyway, the point is we only had Mad Libs to play, and we loved it! And now you must play!

We’ll write a program called mad.py  which reads a file given as a positional argument and finds all the placeholders noted in angle brackets like <verb>  or <adjective> . For each placeholder, we’ll prompt the user for the part of speech being requested like “Give me a verb” and “Give me an adjective.” (Notice that you’ll need to use the correct article.) Each value from the user replaces the placeholder in the text, and if the user says “drive” for “verb,” then <verb>  in the text replaces with drive . When all the placeholders have been replaced with inputs from the user, print out the new text.

#python #regular-expressions #python-programming #python3 #mad libs: using regular expressions #using regular expressions

Regular Expressions in Python [With Examples]: How to Implement?

While processing raw data from any source, extracting the right information is important so that meaningful insights can be obtained from the data. Sometimes it becomes difficult to take out the specific pattern from the data especially in the case of textual data.

The textual data consist of paragraphs of information collected via survey forms, scrapping websites, and other sources. The Channing of different string accessors with pandas functions or other custom functions can get the work done, but what if a more specific pattern needs to be obtained? Regular expressions do this job with ease.

What is a Regular Expression (RegEx)?

Examples to Understand The Workaround

How to Implement it in Python?

Conclusion

#data science #python #regular expression #regular expression in python

Regular Expressions in Python [With Examples]: How to Implement? | upGrad blog

While processing raw data from any source, extracting the right information is important so that meaningful insights can be obtained from the data. Sometimes it becomes difficult to take out the specific pattern from the data especially in the case of textual data.

The textual data consist of paragraphs of information collected via survey forms, scrapping websites, and other sources. The Channing of different string accessors with pandas functions or other custom functions can get the work done, but what if a more specific pattern needs to be obtained? Regular expressions do this job with ease.

What is a Regular Expression (RegEx)?

A regular expression is a representation of a set of characters for strings. It presents a generalized formula for a particular pattern in the strings which helps in segregating the right information from the pool of data. The expression usually consists of symbols or characters that help in forming the rule but, at first glance, it may seem weird and difficult to grasp. These symbols have associated meanings that are described here.

Meta-characters in RegEx

  1. ‘.’: is a wildcard, matches a single character (any character, but just once)
  2. ^: denotes start of the string
  3. $: denotes the end of the string
  4. [ ]: matches one of the sets of characters within [ ]
  5. [a-z]: matches one of the range of characters a,b,…,z
  6. [^abc] : matches a character that is not a,b or c.
  7. a|b: matches either a or b, where a and b are strings
  8. () : provides scoping for operators
  9. \ : enables escape for special characters (\t, \n, \b, .)
  10. \b: matches word boundary
  11. \d : any digit, equivalent to [0-9]
  12. \D: any non digit, equivalent to [^0-9]
  13. \s : any whitespace, equivalent to [ \t\n\r\f\v]
  14. \S : any non-whitespace, equivalent to [^\t\n\r\f\v]
  15. \w : any alphanumeric, equivalent to [a-zA-Z0-9_]
  16. \W : any non-alphanumeric, equivalent to [^a-zA-Z0-9_]
  17. ‘*’: matches zero or more occurrences
  18. ‘+’: matches one or more occurrences
  19. ‘?’: matches zero or one occurrence
  20. {n}: exactly n repetitions, n>=0
  21. {n,}: at least n repetitions
  22. {,n}: at most n repetitions
  23. {m,n}: at least m repetitions and at most n repetitions

#data science #python #regular expression #regular expression in python

Art  Lind

Art Lind

1602968400

Python Tricks Every Developer Should Know

Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

Let’s get started

Swapping value in Python

Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead

>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName 
>>> print(FirstName, LastName)
('Jordan', 'kalebu')

#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development