DEV Community

Weerasak Chongnguluam
Weerasak Chongnguluam

Posted on • Edited on

3

3 ท่า Regular Expression pattern ง่ายๆ ที่ได้ใช้บ่อยๆ

RegEx อาจจะอ่านอยาก แต่ที่ใช้บ่อยๆนั้นไม่ซับซ้อนเลย โพสต์นี้จะลิสต์ที่ใช้ประจำเท่าที่จำได้ออกมาให้ดู

1. ค้นบรรทัดที่ขึ้นต้นด้วย pattern ที่ต้องการ

เช่นใน Go ฟังก์ชันนั้นประกาศด้วย func ขึ้นต้นแน่ๆ เราสามารถใช้ ^ ช่วยได้เพื่อกรองเอาแค่การประกาศฟังก์ชันเท่านั้นโดยใส่ ^ ข้างหน้าสิ่งที่ต้องการค้นเช่น ^func

2. ค้นบรรทัดที่ลงท้ายด้วย pattern ที่ต้องการ

เช่นเราอยากหาการประกาศฟังก์ชันของ Go ที่ return error type กลับออกมา ซึ่งมันจะต้องลงท้ายด้วย error { แน่ๆ เราก็ใช้ $ ช่วยได้ โดยส่งไปที่ท้ายของ pattern ที่ต้องการค้นหาเช่น error {$

3. ใช้ .* ตรงส่วนที่เราไม่สนใจ อยากให้มันเป็นอะไรก็ได้

เช่นจากสองข้อเมื่อกี้ถ้าเราเอามาประกอบกัน อยากหา func ที่ลงด้ายด้วย error { เพื่อให้การค้นหาเจอสิ่งที่ต้องการมากขึ้น เราจะใช้ทั้ง ^ เพื่อระบุสิ่งที่อยู่ข้างหน้า ใช้ $ เพื่อระบุสิ่งที่อยู่ข้างหลัง และ .* เพื่อบอกว่าตรงกลางระหว่างนี้เป็นอะไรก็ได้แบบนี้ ^func.*error {$

Buy Me A Coffee

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay