Tôi nghĩ rằng đây không những gì bạn cần:
\w+\s?(\d{1,2})?(:\d{1,2})?([-–]\d{1,2})?(,\s\d{1,2}[-–]\d{1,2})?
Giả định:
- Những con số luôn trong bộ 1 hoặc 2 số
- Các dấu gạch ngang sẽ phù hợp với một trong hai điều sau đây
-
và –
Dưới đây là regex với ý kiến:
"
\w # Match a single character that is a “word character” (letters, digits, and underscores)
+ # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
\s # Match a single character that is a “whitespace character” (spaces, tabs, and line breaks)
? # Between zero and one times, as many times as possible, giving back as needed (greedy)
( # Match the regular expression below and capture its match into backreference number 1
\d # Match a single digit 0..9
{1,2} # Between one and 2 times, as many times as possible, giving back as needed (greedy)
)? # Between zero and one times, as many times as possible, giving back as needed (greedy)
( # Match the regular expression below and capture its match into backreference number 2
: # Match the character “:” literally
\d # Match a single digit 0..9
{1,2} # Between one and 2 times, as many times as possible, giving back as needed (greedy)
)? # Between zero and one times, as many times as possible, giving back as needed (greedy)
( # Match the regular expression below and capture its match into backreference number 3
[-–] # Match a single character present in the list “-–”
\d # Match a single digit 0..9
{1,2} # Between one and 2 times, as many times as possible, giving back as needed (greedy)
)? # Between zero and one times, as many times as possible, giving back as needed (greedy)
( # Match the regular expression below and capture its match into backreference number 4
, # Match the character “,” literally
\s # Match a single character that is a “whitespace character” (spaces, tabs, and line breaks)
\d # Match a single digit 0..9
{1,2} # Between one and 2 times, as many times as possible, giving back as needed (greedy)
[-–] # Match a single character present in the list “-–”
\d # Match a single digit 0..9
{1,2} # Between one and 2 times, as many times as possible, giving back as needed (greedy)
)? # Between zero and one times, as many times as possible, giving back as needed (greedy)
"
Và đây là một số ví dụ về việc sử dụng của nó trong php:
if (preg_match('/\w+\s?(\d{1,2})?(:\d{1,2})?([-–]\d{1,2})?(,\s\d{1,2}[-–]\d{1,2})?/', $subject)) {
# Successful match
} else {
# Match attempt failed
}
Nhận một mảng của tất cả các kết quả phù hợp trong một chuỗi đã cho
preg_match_all('/\w+\s?(\d{1,2})?(:\d{1,2})?([-–]\d{1,2})?(,\s\d{1,2}[-–]\d{1,2})?/', $subject, $result, PREG_PATTERN_ORDER);
$result = $result[0];
Vì vậy, nó phải phù hợp ngay cả khi nó chỉ là tên của cuốn sách? Bạn có danh sách các sách cần khớp không? Nếu không nó sẽ chỉ phù hợp với mọi từ. – JJJ
Chỉ cần phù hợp với bất kỳ từ nào, vấn đề thực sự đối với tôi là có quá nhiều phần tùy chọn. – Dziamid