Chuyển đến nội dung chính
eLearner.app
Mô-đun 4 · Bài học 3 trong tổng số 415/32 trong khóa học~10 min
Bài học theo mô-đun (3/4)

Nhóm không bắt giữ: `(?:...)`

Often parentheses are needed only to group (quantify, alternate) and NOT to extract the value. In that case use the non-capturing version: (?:...). It works identically to (...) but does not create a numbered group.

Code
Pattern: (?:https?)://(\w+\.\w+)
Sample:  https://example.com e http://test.org
Match e gruppi:
  match  = "https://example.com"   gruppo1 = "example.com"
  match  = "http://test.org"        gruppo1 = "test.org"

(?:https?) groups the scheme to apply the ? quantifier, but we are not interested in extracting https as a group: group 1 is directly the domain.

Why use it

  1. Readability: the reader immediately understands that the group is only there for structure, not to extract a value.
  2. Performance: the engine does not have to store the group's match.
  3. Clean numbering: numbered groups stay aligned with "information I actually need", without interference.

Optimizing with non-capturing groups

Using (?:...) tells the engine to apply grouping and quantifier rules without wasting memory storing intermediate match results. This is highly recommended in heavy loops or very long text processing.

Try it

tập thể dục#regex.m4.l3.e1
Nỗ lực: 0Đang tải…

Extract the domain (`example.com`, `test.org`…) from every URL in the text. Use `(?:https?)` for the protocol (no need to capture it) and a single group for the domain.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Change the first group from (https?) to (?:https?): no need to capture it, you only want the domain.

Giải pháp khả dụng sau 3 lần thử

Review exercise

tập thể dục#regex.m4.l3.e2
Nỗ lực: 0Đang tải…

Find every repetition of `ab` as a single match, but WITHOUT capturing the group (since you only need the whole match).

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Same syntax as the previous lesson, but with (?:ab)+ instead of (ab)+.

Giải pháp khả dụng sau 3 lần thử

Additional challenge

tập thể dục#regex.m4.l3.e3
Nỗ lực: 0Đang tải…

Find price digits followed optionally by decimal parts inside a non-capturing group, e.g. `100` or `100.50`.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Use (?:\.\d{2})? to make the decimal part optional without capturing it.

Giải pháp khả dụng sau 3 lần thử