Hướng dẫn kiểm tra chuỗi "Bắt đầu bằng khoảng trắng hoặc không" và "Kết thúc bằng khoảng trắng hoặc không"

Cập nhật ngày 15/03/2024
Lượt xem: 51

Regex: Specify "space or start of string" and "space or end of string"

 

You can use any of the following:

\b      #A word break and will work for both spaces and end of lines.
(^|\s)  #the | means or. () is a capturing group. 


/\b(stackoverflow)\b/

Also, if you don't want to include the space in your match, you can use lookbehind/aheads.

(?<=\s|^)         #to look behind the match
(stackoverflow)   #the string you want. () optional
(?=\s|$)          #to look ahead.

(^|\s) would match space or start of string and ($|\s) for space or end of string. Together it's:

(^|\s)stackoverflow($|\s)

Here's what I would use:

(?<!\S)stackoverflow(?!\S)

In other words, match "stackoverflow" if it's not preceded by a non-whitespace character and not followed by a non-whitespace character.

This is neater (IMO) than the "space-or-anchor" approach, and it doesn't assume the string starts and ends with word characters like the \b approach does.

Source: https://newbedev.com/regex-specify-space-or-start-of-string-and-space-or-end-of-string