30 regular expressions that web developers should know

{1}s[a-zA-Z0-9s.#]+[;]{1}

Có thể rất hiếm để chạy regex trên CSS nhưng nó không phải là một tình huống lạ.

Đoạn mã này có thể được sử dụng để lấy ra mọi thuộc tính và giá trị CSS khớp từ selector cụ thể. Nó có thể được sử dụng cho bất kỳ lý do nào, ví dụ như loại bỏ thuộc tính trùng lặp.

21. Loại bỏ chú thích HTML

Nếu vì bất cứ lý do nào mà bạn cần phải loại bỏ tất cả các chú thích từ một khối HTML thì đây là mã regex cần dùng. Bạn sẽ tìm thấy một ví dụ PHP sử dụng preg_replace.

22. URL trang cá nhân Facebook

Facebook rất phổ biến và có nhiều sự sắp đặt URL khác nhau. Trong một tình huống mà bạn đang lấy URL hồ sơ từ người sử dụng thì đoạn regex này có thể hữu ích để phân tích chuỗi và xác nhận rằng chúng có cấu trúc đúng. Đoạn này có thể làm chính xác điều đó và nó hoàn hảo cho tất cả các kiểu liên kết FB.

23. Kiểm tra phiên bản Internet Explorer

Trình duyệt IE vẫn đang có thị phần người dùng lớn và các nhà phát triển thường phải kiểm tra phiên bản IE để xử lý tính tương thích của trang web.

Đoạn này có thể được sử dụng trong JavaScript để kiểm tra phiên bản của Internet Explorer (5-11) đang được sử dụng dựa trên chuỗi User-Agent.

24. Bóc tách giá

Giá cả đi kèm trong một loạt các định dạng có chứa số thập phân, dấu phẩy và ký hiệu tiền tệ. Biểu thức này có thể kiểm tra tất cả các định dạng khác nhau để lấy ra một mức giá từ bất kỳ chuỗi nào.

25. Phân tích tiêu đề Email

Với một dòng code này bạn có thể phân tích thông qua một tiêu đề email để lấy ra thông tin “to” từ tiêu đề. Nó có thể được sử dụng song song với nhiều email liên kết với nhau.

26. Khớp một loại tập tin cụ thể

Khi bạn đang làm việc với các định dạng tập tin khác nhau như .xml, .html và .js, nó có thể giúp kiểm tra các tập tin cả nội bộ (local) và được tải lên bởi người dùng. Đoạn này lấy ra một phần mở rộng tập tin để kiểm tra xem nó có giá trị nằm trong một danh sách các phần mở rộng hợp lệ hay không.

27. Khớp một chuỗi URL

Đoạn này có thể sử dụng cho cả chuỗi HTTP và HTTPS để kiểm tra xem nó có khớp với cú pháp tên miền mức cao nhất (TLD) hay không. Cũng có một phiên bản đơn giản hơn đoạn này sử dụng RegExp của JavaScript.

28. Thêm rel=”nofollow” vào các liên kết

Nếu bạn đang làm việc với hàng loạt mã HTML có thể nó thật khủng khiếp khi phải làm thủ công các nhiệm vụ lặp đi lặp lại. Biểu thức chính quy là hoàn hảo cho công việc này và họ sẽ tiết kiệm được rất nhiều thời gian.

Đoạn regex này có thể lấy ra tất cả liên kết từ một khối HTML và thêm thuộc tính rel=”nofollow” vào mỗi phần tử.

29. Khớp Media Query

Chia tách các Media Query CSS vào từng tham số và thuộc tính của chúng. Điều này có thể giúp bạn phân tích CSS bên ngoài với sự tập trung trực tiếp hơn vào cách mà code hoạt động.

30. Cú pháp tìm kiếm Google

Bạn có thể xây dựng mã regex của riêng bạn cho các thao tác tìm kiếm nội dung bằng cách sử dụng cú pháp độc quyền của Google. Các dấu cộng (+) biểu thị các từ khóa bổ sung và dấu trừ (-) biểu thị rằng nên bỏ qua và loại bỏ khỏi kết quả.

Đó là một đoạn khá phức tạp nhưng được sử dụng đúng cách thì nó có thể cung cấp một cơ sở cho việc xây dựng thuật toán tìm kiếm của riêng bạn.

ITZone via kipalog

Regular expressions (or regex) is a powerful tool that every developer should know. It can match a string of characters based on very complex parameters that can save you a lot of time when building dynamic websites.

Although Web developers face more different tasks than software developers, most of them still have the same platform code. Regular expressions are somewhat difficult to learn at first, but can be very powerful when used correctly.

The hardest part is learning the syntax and learning how to write your own regex code from scratch. To save time, I picked up 30 different regex code segments that you can use in your projects. And since regex is not limited to a specific language, you can apply the following paragraphs to any language from Javascript to PHP or Python.

1. Strength of password

Checking the strength of a password is often subjective so there is no absolute answer. But I feel this regex is a great starting point if you don't want to have to write your password strength test separately from scratch.

2. Color code Hex

Hex color codes are very popular in the field of web development. This regex can be used to get the appropriate hex code from any string for any purpose.

3. Validate Email address

One of the most common tasks for a developer is to check if a string is an email address. For PHP, you can use the filter_var function: filter_var ($ email, FILTER_VALIDATE_EMAIL)

4. IPv4 address

Similar to an email address is an IP address – used to identify a specific computer with Internet access. This regular expression checks a string to see if it conforms to the IPv4 address syntax.

5. IPv6 address

Or maybe you want to check an address using the newer IPv6 syntax with this more advanced regex. The difference is very small although it is important in the development process.

6. Thousands separators

This regex code works on any number and will apply any separator you choose for each third digit separated into thousands, millions, …

7. Add HTTP before the link

Whether you are working in JavaScript, Ruby or PHP, this expression can be very helpful. It will check any URL string to see if it has an HTTP / HTTPS prefix, and if not, prepend the string accordingly.

8. Get the domain name from the URL

Each website domain contains a protocol at the beginning (HTTP or HTTPS) and sometimes has a subdomain with an additional page path. You can use this regex to cut through all that and return only the domain name.

9. Arrange the keywords by counting the number of words

Those who use Google Analytics and Webmaster Tools will really like this regular expression. It can sort keywords based on the number of words used in a search.

This can be specific number (ie only 5 words) or it can match a series of words (ie 2 or more). When used to organize and analyze data, it is one of the powerful regular expressions.

10. Find a valid Base64 string in PHP

If you are a PHP developer, you may sometimes need to analyze through code to search for Base64 encoded binary objects (for example, find a hidden shell in a PHP file). This regex is applicable to all PHP code and will check for any existing Base64 string.

11. Authenticate phone numbers

Short, sweet and straight to the point. This regex segment will authenticate any phone number syntax based on US phone number style.

This can turn into a rather complex topic, I recommend skimming through this stack topic for a more detailed answer.

12. White space at the beginning and end

Use this code to get the beginning / end spaces from a string. This may not be a big deal, but sometimes it affects the output when retrieving the results from a database or applying to document encryption.

13. Get the image source

If for some reason you need to extract a source image directly from HTML, this code is the perfect solution. Although it can run smoothly on Backend, JS developers should rely on jQuery's .attr () method for Frontend.

14. Validate date in DD / MM / YYYY format

The days are difficult because they can appear as text + numbers, or just numbers in different formats. PHP has a great date function but this is not always the best option when extracting from a raw string. Consider replacing by using this regular expression for specific date syntax.

15. Match ID Youtube Video

Youtube has kept the same URL structure for years just because it works. This is also the most popular video sharing site on the web, so YouTube videos tend to coordinate the most traffic.

If you need to retrieve a Youtube video ID from a URL, this regex is perfect and works well with all variations of the URL YouTube structure.

16. ISBN authentication

Books are printed in a digital system called ISBN. This can be quite difficult when you consider the difference between ISBN-10 and ISBN-13.

However, this amazing regex allows you to confirm an ISBN number and check if it is ISBN10 or 13. All the code is written in PHP so this may seem particularly useful for the home. web development.

17. Check the postal code

The author of this regex not only shares it for free but also takes the time to explain it. You will find it useful even if you are matching a 5-digit postal code or a longer 9-digit version.

Remember that it is primarily for the US postal system, so you may need to adjust for other countries.

18. Valid Twitter username

This is a very small regex code to match the Twitter username found in a string. It checks based on the syntax mentioned ( @mention ).

19. Credit card number

Credit card number authentication often requires a secure server platform. But regex can be used for the minimum requirements of some typical credit cards.

20. Find CSS properties

It may be very rare to run regex on CSS but it is not a strange situation.

This code can be used to retrieve all CSS properties and values ​​from a specific selector. It can be used for any reason, such as removing duplicate properties.

21. Remove HTML annotations

If for any reason you need to remove all comments from an HTML block, this is the regex code to use. You will find a PHP example using preg_replace .

22. Facebook personal page URL

Facebook is very popular and has many different URL settings. In a situation where you are retrieving the profile URL from the user, this regex segment can be useful for string analysis and confirm that they have the correct structure. This paragraph can do exactly that and it's perfect for all FB link types.

23. Check Internet Explorer version

The IE browser still has a large market share of users and developers often have to check the IE version to handle site compatibility.

This paragraph can be used in JavaScript to check that the version of Internet Explorer (5-11) is being used based on the User-Agent string.

24. Remove prices

Prices come in a variety of formats that contain decimal numbers, commas and currency symbols. This expression can check all different formats to get a price from any string.

25. Analyze Email header

With this line of code you can analyze through an email header to retrieve "big" information from the title. It can be used in tandem with multiple emails linked together.

26. Match a specific file type

When you are working with different file formats like .xml, .html and .js, it can help check files both locally (local) and uploaded by users. This section retrieves a file extension to check if it has a value in a list of valid extensions.

27. Match a URL string

This paragraph can be used for both HTTP and HTTPS strings to check if it matches the top-level domain syntax (TLD). There is also a simpler version of this section that uses RegExp of JavaScript.

28. Add rel = "nofollow" to the links

If you are working with a lot of HTML code, it might be awful to manually do repetitive tasks. Regular expressions are perfect for this job and they will save a lot of time.

This regex segment can retrieve all links from an HTML block and add the rel = "nofollow" attribute to each element.

29. Media Query Joints

Split the CSS Media Query into each of their parameters and properties. This can help you analyze external CSS with a more direct focus on how the code works.

30. Google search syntax

You can build your own regex code for content search operations using Google's proprietary syntax. The plus sign (+) denotes additional keywords and the minus sign (-) indicates that it should be ignored and removed from the result.

It is a rather complex piece but used correctly, it can provide a basis for building your own search algorithm.

ITZone via kipalog

Share the news now