Mô đun:String
| Mô đun Lua này được sử dụng trong thông báo hệ thống, và ở khoảng 467.000 trang, chiếm ≈ 10% tổng số trang. Thay đổi đến nó có thể dẫn đến thay đổi ngay lập tức giao diện người dùng Wikipedia. Để tránh gây lỗi trên quy mô lớn và tải máy chủ không cần thiết, tất cả thay đổi cần được thử nghiệm ở trang con /sandbox, /testcases của mô đun, hoặc ở chỗ thử mô đun. Các thay đổi đã được thử nghiệm có thể thêm vào mô đun bằng một sửa đổi duy nhất. Xin hãy thảo luận các thay đổi tại trang thảo luận trước khi áp dụng sửa đổi. |
| Mô đun này được xếp loại là đã sẵn sàng để sử dụng rộng rãi. Nó đã đạt đến mức độ hoàn thiện, được coi là khá ổn định và không có lỗi, và có thể được sử dụng bất kỳ chỗ nào nếu phù hợp. Nó có thể được nêu trên các trang trợ giúp cũng như các tài liệu Wikipedia khác làm tùy chọn tìm hiểu cho người dùng mới. Để giảm tải tài nguyên máy chủ và tránh tạo đầu ra gây hại, mọi cải tiến nên được thực hiện thông qua việc kiểm thử tại chỗ thử thay vì sửa đổi "thử và sai" lặp đi lặp lại liên tục. |
| Trang mô đun này đang bị khóa không cho sửa đổi. Xem quy định khóa trang và nhật trình khóa để biết thêm chi tiết. Vui lòng thảo luận bất kỳ thay đổi nào tại trang thảo luận; bạn có thể yêu cầu sửa trang này để yêu cầu bảo quản viên sửa đổi trang nếu sửa đổi đó là sửa đổi không gây hại hoặc được chấp nhận sự đồng thuận. Bạn cũng có thể yêu cầu mở khóa trang này. |
Mô đun:String (sửa | thảo luận | lịch sử | liên kết | theo dõi | nhật trình)
Mô đun này nhằm cung cấp quyền truy cập vào các hàm xử lý chuỗi cơ bản.
Hầu hết các hàm được cung cấp ở đây có thể được gọi bằng tham số có tên, tham số không tên hoặc kết hợp cả hai. Nếu sử dụng tham số có tên, Mediawiki sẽ tự động loại bỏ mọi khoảng trắng ở đầu hoặc cuối tham số. Tùy thuộc vào mục đích sử dụng, có thể có lợi khi giữ lại hoặc loại bỏ các khoảng trắng đó.
Các tùy chọn toàn cục
[sửa mã nguồn]- ignore_errors
- Nếu đặt là 'true' hoặc 1, bất kỳ điều kiện lỗi nào sẽ trả về một chuỗi rỗng thay vì thông báo lỗi.
- error_category
- Nếu xảy ra lỗi, chỉ định tên của thể loại để đưa vào thông báo lỗi. Thể loại mặc định là Thể loại:Trang gây lỗi trong mô đun String (0).
- no_category
- Nếu đặt là 'true' hoặc 1, sẽ không có thể loại nào được thêm vào nếu xảy ra lỗi.
Các kiểm thử đơn vị cho mô đun này có tại Module:String/testcases.
len
[sửa mã nguồn]Hàm này trả về độ dài của chuỗi mục tiêu.
Cách dùng:
{{#invoke:String|len|chuỗi_mục_tiêu}}
HOẶC
{{#invoke:String|len|s= chuỗi_mục_tiêu }}
Các tham số:
- s
- Chuỗi cần lấy độ dài
Ví dụ:
{{#invoke:String|len| abcdefghi }}→ 11{{#invoke:String|len|s= abcdefghi }}→ 9
sub
[sửa mã nguồn]Hàm này trả về một chuỗi con của chuỗi mục tiêu tại các chỉ mục được chỉ định (bao gồm cả chỉ mục đó), đánh số bắt đầu từ 1.
Cách dùng:
{{#invoke:String|sub|chuỗi_mục_tiêu|chỉ_mục_đầu|chỉ_mục_cuối}}
HOẶC
{{#invoke:String|sub|s= chuỗi_mục_tiêu |i= chỉ_mục_đầu |j= chỉ_mục_cuối }}
Các tham số:
- s
- Chuỗi cần lấy tập con
- i
- Chỉ mục đầu tiên của chuỗi con cần lấy, mặc định là 1.
- j
- Chỉ mục cuối cùng của chuỗi con cần lấy, mặc định là ký tự cuối cùng.
Ký tự đầu tiên của chuỗi được gán chỉ mục là 1. Nếu i hoặc j là giá trị âm, nó được hiểu là chọn ký tự bằng cách đếm ngược từ cuối chuỗi. Do đó, giá trị -1 tương đương với việc chọn ký tự cuối cùng của chuỗi.
Nếu các chỉ mục yêu cầu nằm ngoài phạm vi của chuỗi đã cho, lỗi sẽ được báo cáo. Để tránh thông báo lỗi, hãy sử dụng {{#gọi:ustring|sub}} thay thế.
Ví dụ:
"{{#invoke:String|sub| abcdefghi }}"→ " abcdefghi ""{{#invoke:String|sub|s= abcdefghi }}"→ "abcdefghi""{{#invoke:String|sub| abcdefghi | 3 }}"→ "bcdefghi ""{{#invoke:String|sub|s= abcdefghi |i= 3 }}"→ "cdefghi""{{#invoke:String|sub| abcdefghi | 3 | 4 }}"→ "bc""{{#invoke:String|sub|s= abcdefghi |i= 3 |j= 4 }}"→ "cd"
sublength
[sửa mã nguồn]Hàm này thực hiện các tính năng của {{str sub old}} và được giữ lại để duy trì các bản mẫu cũ này. Nó trả về một chuỗi con của chuỗi mục tiêu bắt đầu từ một chỉ mục được chỉ định và có độ dài nhất định.
Cách dùng:
{{#invoke:String|sublength|s= chuỗi_mục_tiêu |i= chỉ_mục_đầu |len= độ_dài }}
Các tham số:
- s
- Chuỗi nguồn
- i
- Chỉ mục bắt đầu của chuỗi con cần trả về. Ký tự đầu tiên của chuỗi được gán chỉ mục là 0.
- len
- Độ dài của chuỗi cần trả về, mặc định là đến ký tự cuối cùng.
Ví dụ:
{{#invoke:String|sublength|s= abcdefghi }}→ abcdefghi{{#invoke:String|sublength|s= abcdefghi |i= 3 }}→ defghi{{#invoke:String|sublength|s= abcdefghi |i= 3 |len= 4 }}→ defg
match
[sửa mã nguồn]Hàm này trả về một chuỗi con từ chuỗi nguồn khớp với một mẫu (pattern) được chỉ định.
Cách dùng:
{{#invoke:String|match|chuỗi_nguồn|chuỗi_mẫu|chỉ_mục_đầu|số_thứ_tự_khớp|cờ_plain|đầu_ra_khi_không_khớp}}
HOẶC
{{#invoke:String|match|s= chuỗi_nguồn |pattern= chuỗi_mẫu |start= chỉ_mục_đầu |match= số_thứ_tự_khớp |plain= cờ_plain |nomatch= đầu_ra_khi_không_khớp }}
Các tham số:
- s
- Chuỗi để tìm kiếm
- pattern
- Mẫu hoặc chuỗi cần tìm trong chuỗi nguồn
- start
- Chỉ mục trong chuỗi nguồn để bắt đầu tìm kiếm. Ký tự đầu tiên của chuỗi có chỉ mục là 1. Mặc định là 1.
- match
- Trong một số trường hợp, có thể có nhiều kết quả khớp trên một chuỗi duy nhất. Tham số này chỉ định kết quả khớp nào sẽ được trả về, trong đó kết quả đầu tiên là match= 1. Nếu chỉ định số âm, kết quả khớp sẽ được đếm ngược từ kết quả cuối cùng. Do đó match = -1 tương đương với yêu cầu kết quả khớp cuối cùng. Mặc định là 1.
- plain
- Cờ boolean chỉ ra rằng mẫu nên được hiểu là văn bản thuần túy và không phải là mẫu Scribunto ustring (một dạng biểu thức chính quy kiểu Lua thân thiện với unicode). Mặc định là false (để thay đổi:
plain=true) - nomatch
- Nếu không tìm thấy kết quả khớp, xuất ra giá trị "nomatch" thay vì lỗi.
- ignore_errors
- Nếu không tìm thấy kết quả khớp và ignore_errors=true, xuất ra chuỗi rỗng thay vì lỗi.
Nếu match_number hoặc start_index nằm ngoài phạm vi của chuỗi đang truy vấn, hàm này sẽ tạo ra lỗi. Lỗi cũng được tạo ra nếu không tìm thấy kết quả khớp. Nếu thêm tham số ignore_errors=true, lỗi sẽ bị chặn và chuỗi rỗng sẽ được trả về khi có bất kỳ thất bại nào.
Để biết thông tin về cách xây dựng mẫu Lua, một dạng của biểu thức chính quy, xem:
Ví dụ:
{{#invoke:String|match| abc123def456 |%d+}}→ 123{{#invoke:String|match|s= abc123def456 |pattern= %d+ }}→ 123{{#invoke:String|match| abc123def456 |%d+|6}}→ 23{{#invoke:String|match|s= abc123def456 |pattern= %d+ |start= 6 }}→ 3{{#invoke:String|match|s= abc123def456 |pattern= %d+ |start= 6 |match= 2 }}→ 456{{#invoke:String|match|s= abc123%d+ |pattern= %d+ }}→ 123{{#invoke:String|match|s= abc123%d+ |pattern= %d+ |plain= true }}→ %d+{{#invoke:String|match|s= abc |pattern= %d }}→ String Module Error: Match not found{{#invoke:String|match|s= abc |pattern= %d |nomatch= Không có ký tự số trong chuỗi }}→ Không có ký tự số trong chuỗi{{#invoke:String|match|s= abc |pattern= %d |ignore_errors= true }}→{{#invoke:String|match|s= 0012001200 |pattern= 0*(%d*) }}→ 12001200
pos
[sửa mã nguồn]Hàm này trả về một ký tự đơn từ chuỗi mục tiêu tại vị trí pos.
Cách dùng:
{{#invoke:String|pos|chuỗi_mục_tiêu|giá_trị_chỉ_mục}}
HOẶC
{{#invoke:String|pos|target= chuỗi_mục_tiêu |pos= giá_trị_chỉ_mục }}
Các tham số:
- target
- Chuỗi cần tìm kiếm
- pos
- Chỉ mục của ký tự cần trả về
Ký tự đầu tiên có giá trị chỉ mục là 1.
Nếu yêu cầu một giá trị âm, hàm này sẽ chọn ký tự bằng cách đếm ngược từ cuối chuỗi. Nói cách khác pos = -1 tương đương với việc yêu cầu ký tự cuối cùng.
Giá trị yêu cầu bằng 0, hoặc lớn hơn độ dài của chuỗi sẽ trả về lỗi.
Ví dụ:
{{#invoke:String|pos| abcdefghi | 4 }}→ c{{#invoke:String|pos|target= abcdefghi |pos= 4 }}→ d
str_find
[sửa mã nguồn]Hàm này sao chép hành vi của {{str_find}}, bao gồm tất cả các đặc điểm kỳ quặc của nó. Hàm này được cung cấp để hỗ trợ các bản mẫu hiện có, nhưng KHÔNG ĐƯỢC KHUYẾN KHÍCH cho mã và bản mẫu mới. Mã mới được khuyến nghị sử dụng hàm "find" để thay thế.
Trả về chỉ mục đầu tiên trong "source" khớp với "target". Việc đánh chỉ mục bắt đầu từ 1, và hàm trả về -1 nếu chuỗi "target" không hiện diện trong "source".
Lưu ý quan trọng: Nếu chuỗi "target" trống / thiếu, hàm này trả về giá trị "1", đây là hành vi thường không mong muốn, và phải được tính toán riêng biệt.
Cách dùng:
{{#invoke:String|str_find|chuỗi_nguồn|chuỗi_mục_tiêu}}
HOẶC
{{#invoke:String|str_find|source= chuỗi_nguồn |target= chuỗi_mục_tiêu }}
Các tham số:
- source
- Chuỗi để tìm kiếm
- target
- Chuỗi cần tìm trong nguồn
Ví dụ:
{{#invoke:String|str_find| abc123def }}→ 1{{#invoke:String|str_find|source= abc123def }}→ 1{{#invoke:String|str_find| abc123def |123}}→ 5{{#invoke:String|str_find|source= abc123def |target= 123 }}→ 4{{#invoke:String|str_find| abc123def |not}}→ -1
find
[sửa mã nguồn]Hàm này cho phép tìm kiếm một chuỗi mục tiêu hoặc mẫu trong một chuỗi khác.
Cách dùng:
{{#invoke:String|find|chuỗi_nguồn|chuỗi_mục_tiêu|chỉ_mục_đầu|cờ_plain}}
HOẶC
{{#invoke:String|find|source= chuỗi_nguồn |target= chuỗi_mục_tiêu |start= chỉ_mục_đầu |plain= cờ_plain }}
Các tham số:
- source
- Chuỗi để tìm kiếm
- target
- Chuỗi hoặc mẫu cần tìm trong nguồn
- start
- Chỉ mục trong chuỗi nguồn để bắt đầu tìm kiếm, mặc định là 1
- plain
- Cờ boolean chỉ ra rằng target nên được hiểu là văn bản thuần túy và không phải là mẫu Scribunto ustring (một dạng biểu thức chính quy kiểu Lua thân thiện với unicode); mặc định là true
Hàm này trả về chỉ mục đầu tiên >= "start" nơi tìm thấy "target" trong "source". Các chỉ mục bắt đầu từ 1. Nếu không tìm thấy "target", hàm trả về 0. Nếu "source" hoặc "target" bị thiếu / trống, hàm này cũng trả về 0.
Hàm này an toàn cho các chuỗi UTF-8.
Ví dụ:
{{#invoke:String|find|abc123def|12}}→ 4{{#invoke:String|find|source=abc123def|target=12}}→ 4{{#invoke:String|find|source=abc123def|target=pqr}}→ 0{{#invoke:String|find| abc123def |123}}→ 5{{#invoke:String|find|source= abc123def |target= 123 }}→ 4{{#invoke:String|find|source=abc123def|target=%d |start=3 |plain=false }}→ 4
Khi sử dụng tham số không tên, khoảng trắng ở đầu và cuối được giữ lại và tính vào:
{{#invoke:String|find| abc123def |c|false}}→ 5{{#invoke:String|find|source= abc123def |target=c|plain=false}}→ 3{{#invoke:string|find|abc 123 def|%s|plain=false}}→ 4
Kiểm tra sự hiện diện của một chuỗi:
{{#ifexpr:{{#invoke:string|find|haystack|needle}}|Found needle|Didn't find needle}}→ Didn't find needle
findpagetext
[sửa mã nguồn]Hàm findpagetext trả về vị trí của một đoạn văn bản trong mã nguồn wikitext của một trang. Nó nhận tối đa bốn tham số:
- Tham số vị trí đầu tiên hoặc |text là văn bản cần tìm kiếm.
- Tham số tùy chọn |title là tiêu đề trang, mặc định là trang hiện tại.
- Tham số tùy chọn |plain là true cho tìm kiếm thuần (mặc định), hoặc false cho tìm kiếm mẫu Lua.
- Tham số tùy chọn |nomatch là giá trị trả về khi không tìm thấy kết quả khớp; mặc định là không có gì.
- Ví dụ
{{#invoke:String |findpagetext |text=Youghiogheny}}→{{#invoke:String |findpagetext |text=Youghiogheny |nomatch=không tìm thấy}}→ không tìm thấy{{#invoke:String |findpagetext |text=Youghiogheny |title=Cầu Boston |nomatch=không tìm thấy}}→ Lỗi Lua: bad argument #1 to 'find' (string expected, got nil).{{#invoke:String |findpagetext |text=sông |title=Cầu Boston |nomatch=không tìm thấy}}→ Lỗi Lua: bad argument #1 to 'find' (string expected, got nil).{{#invoke:String |findpagetext |text=[Ss]ông |title=Cầu Boston |plain=false |nomatch=không tìm thấy}}→ Lỗi Lua: bad argument #1 to 'find' (string expected, got nil).{{#invoke:String |findpagetext |text=%[%[ |title=Cầu Boston |plain=f |nomatch=không tìm thấy}}→ Lỗi Lua: bad argument #1 to 'find' (string expected, got nil).{{#invoke:String |findpagetext |text=%{%{[Cc]oord |title=Cầu Boston |plain=f |nomatch=không tìm thấy}}→ Lỗi Lua: bad argument #1 to 'find' (string expected, got nil).
Việc tìm kiếm có phân biệt chữ hoa chữ thường, do đó cần khớp mẫu Lua để tìm sông hoặc Sông. Ví dụ cuối cùng tìm {{coord và {{Coord. Ví dụ áp chót tìm một liên kết wiki.
Bản mẫu:Findpagetext là một trình bao bọc tiện lợi cho hàm này.
replace (gsub)
[sửa mã nguồn]Lưu ý rằng theo mặc định, mẫu được hiểu là văn bản thuần túy vì cờ plain |plain= mặc định là true. Để sử dụng mẫu Scribunto mw.ustring, bạn phải đặt nó thành false. |
Hàm này cho phép thay thế một chuỗi mục tiêu hoặc mẫu trong một chuỗi khác. Đối với các lập trình viên Lua: hàm này hoạt động nội bộ bằng cách gọi mw.ustring.gsub.
Cách dùng:
{{#invoke:String|replace|chuỗi_nguồn|chuỗi_mẫu|chuỗi_thay_thế|số_lượng_thay_thế|cờ_plain}}
HOẶC
{{#invoke:String|replace|source= chuỗi_nguồn |pattern= chuỗi_mẫu |replace= chuỗi_thay_thế |count= số_lượng_thay_thế |plain= cờ_plain }}
Các tham số:
- source
- Chuỗi để tìm kiếm
- pattern
- Chuỗi hoặc mẫu cần tìm trong nguồn
- replace
- Văn bản thay thế
- count
- Số lần xuất hiện cần thay thế; mặc định là tất cả
- plain
- Cờ boolean chỉ ra rằng mẫu nên được hiểu là văn bản thuần túy và không phải là mẫu Scribunto ustring (một dạng biểu thức chính quy kiểu Lua thân thiện với unicode); mặc định là true
Ví dụ:
"{{#invoke:String|replace| abc123def456 |123|XYZ}}"→ " abcXYZdef456 ""{{#invoke:String|replace|source= abc123def456 |pattern= 123 |replace= XYZ }}"→ "abcXYZdef456""{{#invoke:String|replace| abc123def456 |%d+|XYZ|1|false}}"→ " abcXYZdef456 ""{{#invoke:String|replace|source= abc123def456 |pattern= %d+ |replace= XYZ |count=1 |plain= false }}"→ "abcXYZdef456""{{#invoke:String|replace|source= abc123def456 |pattern= %d+ |replace= XYZ |plain= false }}"→ "abcXYZdefXYZ"{{#invoke:String|replace|source= 0012001200 |pattern= ^0* |plain= false }}→ 12001200
rep
[sửa mã nguồn]Lặp lại một chuỗi n lần. Một hàm đơn giản để chuyển string.rep vào các bản mẫu.
Cách dùng:
{{#invoke:String|rep|nguồn|số_lượng}}
Các tham số:
- source
- Chuỗi cần lặp lại
- count
- Số lần lặp lại.
Ví dụ:
"{{#invoke:String|rep|hello|3}}"→ "hellohellohello""{{#invoke:String|rep| hello | 3 }}"→ " hello hello hello "
escapePattern
[sửa mã nguồn]Trong một mẫu Lua, thay đổi một ký tự lớp thành một ký tự nghĩa đen (literal). Ví dụ: trong một mẫu, ký tự . bắt "bất kỳ ký tự nào"; escapePattern sẽ chuyển đổi nó thành %., chỉ bắt ký tự chấm "." theo nghĩa đen.
Cách dùng:
{{#invoke:String|escapePattern|chuỗi_mẫu}}
Các tham số:
- pattern_string
- Chuỗi mẫu cần thoát (escape)
Ví dụ:
"{{#invoke:String|escapePattern|A.D.}}"→ "A%.D%.""{{#invoke:String|escapePattern|10%}}"→ "10%%"
count
[sửa mã nguồn]Đếm số lần một mẫu nhất định xuất hiện trong các đối số được truyền cho mô đun này. Chỉ đếm các kết quả khớp rời rạc.
Cách dùng:
{{#invoke:String|count|chuỗi_nguồn|chuỗi_mẫu|cờ_plain}}
HOẶC
{{#invoke:String|count|source= chuỗi_nguồn |pattern= chuỗi_mẫu|plain= cờ_plain }}
Các tham số:
- source_string
- Chuỗi để đếm số lần xuất hiện trong đó
- pattern
- Chuỗi hoặc mẫu để đếm số lần xuất hiện trong nguồn
- plain
- Cờ boolean chỉ ra rằng mẫu nên được hiểu là văn bản thuần túy và không phải là mẫu Scribunto ustring (một dạng biểu thức chính quy kiểu Lua thân thiện với unicode); mặc định là true
Ví dụ:
- Đếm chữ 'a':
"{{#invoke:String|count|aabbcc|a}}"→ "2" - Đếm số lần xuất hiện của 'aba':
"{{#invoke:String|count|ababababab|aba}}"→ "2" - Đếm "hoặc 'a' hoặc 'c' ":
"{{#invoke:String|count|aabbcc|[ac]|plain=false}}"→ "4" - Đếm "không phải 'a' ":
"{{#invoke:String|count|aaabaaac|[^a]|plain=false}}"→ "2" - Đếm "bắt đầu bằng 'a' ":
"{{#invoke:String|count|aaabaaac|^a|plain=false}}"→ "1"
join
[sửa mã nguồn]Nối tất cả các chuỗi được truyền dưới dạng đối số thành một chuỗi, coi đối số đầu tiên là dấu phân cách.
Cách dùng:
{{#invoke:String|join|dấu_phân_cách|chuỗi1|chuỗi2|...}}
Các tham số:
- separator
- Chuỗi dùng để phân tách từng chuỗi được nối với nhau
- Lưu ý rằng khoảng trắng ở đầu và cuối dấu phân cách sẽ không bị loại bỏ.
- string1/string2/...
- Các chuỗi được nối với nhau
Ví dụ:
"{{#invoke:String|join|x|foo|bar|baz}}"→ "fooxbarxbaz""{{#invoke:String|join||a|b|c|d|e|f|g}}"→ "abcdefg""{{#invoke:String|join|,|a|b|c|d|e|f|g}}"→ "a,b,c,d,e,f,g""{{#invoke:String|join|, |a|b|c|d|e|f|g}}"→ "a, b, c, d, e, f, g""{{#invoke:String|join| – |a|b|c|d|e|f|g}}"→ "a – b – c – d – e – f – g"
Ví dụ trước sử dụng thực thể html – nhưng ký tự unicode cũng hoạt động.
endswith
[sửa mã nguồn]Cách dùng:
{{#invoke:String|endswith|chuỗi_nguồn|chuỗi_cần_tìm}}
HOẶC
{{#invoke:String|endswith|source= chuỗi_nguồn |pattern= chuỗi_cần_tìm}}
Trả về "yes" nếu chuỗi nguồn kết thúc bằng chuỗi tìm kiếm. Sử dụng các tham số có tên để cắt khoảng trắng của chuỗi trước khi sử dụng. Bất chấp tên tham số, chuỗi_cần_tìm không phải là mẫu Lua, nó được diễn giải theo nghĩa đen.
"{{#invoke:String|endswith|xxxyyy|y}}"→ "yes""{{#invoke:String|endswith|xxxyyy|z}}"→ ""
Xem thêm
[sửa mã nguồn]- {{#invoke:Params|mapping_by_replacing}} và các hàm khác từ cùng mô đun này
- {{#invoke:MultiReplace|main}}
--[=[
Mô đun này nhằm cung cấp các hàm chuỗi cơ bản.
Phần nhiều hàm này cho phép gọi với các tham số có tên, các tham số không có
tên, hoặc pha trộn cả hai kiểu. Nếu sử dụng các tham số có tên, MediaWiki tự
động bỏ qua khoảng cách đằng truớc và đằng sau tham số. Tùy cách sử dụng, bạn có
thể cần giữ hoặc bỏ qua khoảng cách này.
Các tùy chọn toàn cục:
ignore_errors: Nếu là 'true' hoặc 1, bất cứ trạng thái lỗi nào sẽ cho ra
chuỗi rỗng thay vì thông báo lỗi.
error_category: Nếu xuất hiện lỗi, trang được tự động xếp vào thể loại này
và thông báo lỗi sẽ được hiển thị. Thể loại mặc định là
[[Thể loại:Trang gây lỗi trong mô đun String]].
no_category: Nếu là 'true' hoặc 1, trang không được tự động xếp vào thể loại
khi xuất hiện lỗi.
Các trường hợp kiểm thử đơn vị cho mô đun này có sẵn tại [[Module:String/tests]].
]=]
--[[
This module is intended to provide access to basic string functions.
Most of the functions provided here can be invoked with named parameters,
unnamed parameters, or a mixture. If named parameters are used, Mediawiki will
automatically remove any leading or trailing whitespace from the parameter.
Depending on the intended use, it may be advantageous to either preserve or
remove such whitespace.
Global options
ignore_errors: If set to 'true' or 1, any error condition will result in
an empty string being returned rather than an error message.
error_category: If an error occurs, specifies the name of a category to
include with the error message. The default category is
[Category:Errors reported by Module String].
no_category: If set to 'true' or 1, no category will be added if an error
is generated.
Unit tests for this module are available at Module:String/tests.
]]
local str = {}
--[[
len
This function returns the length of the target string.
Usage:
{{#invoke:String|len|target_string|}}
OR
{{#invoke:String|len|s=target_string}}
Parameters
s: The string whose length to report
If invoked using named parameters, Mediawiki will automatically remove any leading or
trailing whitespace from the target string.
]]
function str.len( frame )
local new_args = str._getParameters( frame.args, {'s'} )
local s = new_args['s'] or ''
return mw.ustring.len( s )
end
--[[
sub
This function returns a substring of the target string at specified indices.
Usage:
{{#invoke:String|sub|target_string|start_index|end_index}}
OR
{{#invoke:String|sub|s=target_string|i=start_index|j=end_index}}
Parameters
s: The string to return a subset of
i: The fist index of the substring to return, defaults to 1.
j: The last index of the string to return, defaults to the last character.
The first character of the string is assigned an index of 1. If either i or j
is a negative value, it is interpreted the same as selecting a character by
counting from the end of the string. Hence, a value of -1 is the same as
selecting the last character of the string.
If the requested indices are out of range for the given string, an error is
reported.
]]
function str.sub( frame )
local new_args = str._getParameters( frame.args, { 's', 'i', 'j' } )
local s = new_args['s'] or ''
local i = tonumber( new_args['i'] ) or 1
local j = tonumber( new_args['j'] ) or -1
local len = mw.ustring.len( s )
-- Convert negatives for range checking
if i < 0 then
i = len + i + 1
end
if j < 0 then
j = len + j + 1
end
if i > len or j > len or i < 1 or j < 1 then
return str._error( 'String subset index out of range' )
end
if j < i then
return str._error( 'String subset indices out of order' )
end
return mw.ustring.sub( s, i, j )
end
--[[
This function implements that features of {{str sub old}} and is kept in order
to maintain these older templates.
]]
function str.sublength( frame )
local i = tonumber( frame.args.i ) or 0
local len = tonumber( frame.args.len )
return mw.ustring.sub( frame.args.s, i + 1, len and ( i + len ) )
end
--[[
_match
This function returns a substring from the source string that matches a
specified pattern. It is exported for use in other modules
Usage:
strmatch = require("Module:String")._match
sresult = strmatch( s, pattern, start, match, plain, nomatch )
Parameters
s: The string to search
pattern: The pattern or string to find within the string
start: The index within the source string to start the search. The first
character of the string has index 1. Defaults to 1.
match: In some cases it may be possible to make multiple matches on a single
string. This specifies which match to return, where the first match is
match= 1. If a negative number is specified then a match is returned
counting from the last match. Hence match = -1 is the same as requesting
the last match. Defaults to 1.
plain: A flag indicating that the pattern should be understood as plain
text. Defaults to false.
nomatch: If no match is found, output the "nomatch" value rather than an error.
For information on constructing Lua patterns, a form of [regular expression], see:
* http://www.lua.org/manual/5.1/manual.html#5.4.1
* http://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#Patterns
* http://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#Ustring_patterns
]]
-- This sub-routine is exported for use in other modules
function str._match( s, pattern, start, match_index, plain_flag, nomatch )
if s == '' then
return str._error( 'Target string is empty' )
end
if pattern == '' then
return str._error( 'Pattern string is empty' )
end
start = tonumber(start) or 1
if math.abs(start) < 1 or math.abs(start) > mw.ustring.len( s ) then
return str._error( 'Requested start is out of range' )
end
if match_index == 0 then
return str._error( 'Match index is out of range' )
end
if plain_flag then
pattern = str._escapePattern( pattern )
end
local result
if match_index == 1 then
-- Find first match is simple case
result = mw.ustring.match( s, pattern, start )
else
if start > 1 then
s = mw.ustring.sub( s, start )
end
local iterator = mw.ustring.gmatch(s, pattern)
if match_index > 0 then
-- Forward search
for w in iterator do
match_index = match_index - 1
if match_index == 0 then
result = w
break
end
end
else
-- Reverse search
local result_table = {}
local count = 1
for w in iterator do
result_table[count] = w
count = count + 1
end
result = result_table[ count + match_index ]
end
end
if result == nil then
if nomatch == nil then
return str._error( 'Match not found' )
else
return nomatch
end
else
return result
end
end
--[[
match
This function returns a substring from the source string that matches a
specified pattern.
Usage:
{{#invoke:String|match|source_string|pattern_string|start_index|match_number|plain_flag|nomatch_output}}
OR
{{#invoke:String|match|s=source_string|pattern=pattern_string|start=start_index
|match=match_number|plain=plain_flag|nomatch=nomatch_output}}
Parameters
s: The string to search
pattern: The pattern or string to find within the string
start: The index within the source string to start the search. The first
character of the string has index 1. Defaults to 1.
match: In some cases it may be possible to make multiple matches on a single
string. This specifies which match to return, where the first match is
match= 1. If a negative number is specified then a match is returned
counting from the last match. Hence match = -1 is the same as requesting
the last match. Defaults to 1.
plain: A flag indicating that the pattern should be understood as plain
text. Defaults to false.
nomatch: If no match is found, output the "nomatch" value rather than an error.
If invoked using named parameters, Mediawiki will automatically remove any leading or
trailing whitespace from each string. In some circumstances this is desirable, in
other cases one may want to preserve the whitespace.
If the match_number or start_index are out of range for the string being queried, then
this function generates an error. An error is also generated if no match is found.
If one adds the parameter ignore_errors=true, then the error will be suppressed and
an empty string will be returned on any failure.
For information on constructing Lua patterns, a form of [regular expression], see:
* http://www.lua.org/manual/5.1/manual.html#5.4.1
* http://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#Patterns
* http://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#Ustring_patterns
]]
-- This is the entry point for #invoke:String|match
function str.match( frame )
local new_args = str._getParameters( frame.args, {'s', 'pattern', 'start', 'match', 'plain', 'nomatch'} )
local s = new_args['s'] or ''
local start = tonumber( new_args['start'] ) or 1
local plain_flag = str._getBoolean( new_args['plain'] or false )
local pattern = new_args['pattern'] or ''
local match_index = math.floor( tonumber(new_args['match']) or 1 )
local nomatch = new_args['nomatch']
return str._match( s, pattern, start, match_index, plain_flag, nomatch )
end
--[[
pos
This function returns a single character from the target string at position pos.
Usage:
{{#invoke:String|pos|target_string|index_value}}
OR
{{#invoke:String|pos|target=target_string|pos=index_value}}
Parameters
target: The string to search
pos: The index for the character to return
If invoked using named parameters, Mediawiki will automatically remove any leading or
trailing whitespace from the target string. In some circumstances this is desirable, in
other cases one may want to preserve the whitespace.
The first character has an index value of 1.
If one requests a negative value, this function will select a character by counting backwards
from the end of the string. In other words pos = -1 is the same as asking for the last character.
A requested value of zero, or a value greater than the length of the string returns an error.
]]
function str.pos( frame )
local new_args = str._getParameters( frame.args, {'target', 'pos'} )
local target_str = new_args['target'] or ''
local pos = tonumber( new_args['pos'] ) or 0
if pos == 0 or math.abs(pos) > mw.ustring.len( target_str ) then
return str._error( 'String index out of range' )
end
return mw.ustring.sub( target_str, pos, pos )
end
--[[
str_find
This function duplicates the behavior of {{str_find}}, including all of its quirks.
This is provided in order to support existing templates, but is NOT RECOMMENDED for
new code and templates. New code is recommended to use the "find" function instead.
Returns the first index in "source" that is a match to "target". Indexing is 1-based,
and the function returns -1 if the "target" string is not present in "source".
Important Note: If the "target" string is empty / missing, this function returns a
value of "1", which is generally unexpected behavior, and must be accounted for
separatetly.
]]
function str.str_find( frame )
local new_args = str._getParameters( frame.args, {'source', 'target'} )
local source_str = new_args['source'] or ''
local target_str = new_args['target'] or ''
if target_str == '' then
return 1
end
local start = mw.ustring.find( source_str, target_str, 1, true )
if start == nil then
start = -1
end
return start
end
--[[
find
This function allows one to search for a target string or pattern within another
string.
Usage:
{{#invoke:String|find|source_str|target_string|start_index|plain_flag}}
OR
{{#invoke:String|find|source=source_str|target=target_str|start=start_index|plain=plain_flag}}
Parameters
source: The string to search
target: The string or pattern to find within source
start: The index within the source string to start the search, defaults to 1
plain: Boolean flag indicating that target should be understood as plain
text and not as a Lua style regular expression, defaults to true
If invoked using named parameters, Mediawiki will automatically remove any leading or
trailing whitespace from the parameter. In some circumstances this is desirable, in
other cases one may want to preserve the whitespace.
This function returns the first index >= "start" where "target" can be found
within "source". Indices are 1-based. If "target" is not found, then this
function returns 0. If either "source" or "target" are missing / empty, this
function also returns 0.
This function should be safe for UTF-8 strings.
]]
function str.find( frame )
local new_args = str._getParameters( frame.args, {'source', 'target', 'start', 'plain' } )
local source_str = new_args['source'] or ''
local pattern = new_args['target'] or ''
local start_pos = tonumber(new_args['start']) or 1
local plain = new_args['plain'] or true
if source_str == '' or pattern == '' then
return 0
end
plain = str._getBoolean( plain )
local start = mw.ustring.find( source_str, pattern, start_pos, plain )
if start == nil then
start = 0
end
return start
end
--[[
replace
This function allows one to replace a target string or pattern within another
string.
Usage:
{{#invoke:String|replace|source_str|pattern_string|replace_string|replacement_count|plain_flag}}
OR
{{#invoke:String|replace|source=source_string|pattern=pattern_string|replace=replace_string|
count=replacement_count|plain=plain_flag}}
Parameters
source: The string to search
pattern: The string or pattern to find within source
replace: The replacement text
count: The number of occurences to replace, defaults to all.
plain: Boolean flag indicating that pattern should be understood as plain
text and not as a Lua style regular expression, defaults to true
]]
function str.replace( frame )
local new_args = str._getParameters( frame.args, {'source', 'pattern', 'replace', 'count', 'plain' } )
local source_str = new_args['source'] or ''
local pattern = new_args['pattern'] or ''
local replace = new_args['replace'] or ''
local count = tonumber( new_args['count'] )
local plain = new_args['plain'] or true
if source_str == '' or pattern == '' then
return source_str
end
plain = str._getBoolean( plain )
if plain then
pattern = str._escapePattern( pattern )
replace = mw.ustring.gsub( replace, "%%", "%%%%" ) --Only need to escape replacement sequences.
end
local result
if count ~= nil then
result = mw.ustring.gsub( source_str, pattern, replace, count )
else
result = mw.ustring.gsub( source_str, pattern, replace )
end
return result
end
--[[
simple function to pipe string.rep to templates.
]]
function str.rep( frame )
local repetitions = tonumber( frame.args[2] )
if not repetitions then
return str._error( 'function rep expects a number as second parameter, received "' .. ( frame.args[2] or '' ) .. '"' )
end
return string.rep( frame.args[1] or '', repetitions )
end
--[[
escapePattern
This function escapes special characters from a Lua string pattern. See [1]
for details on how patterns work.
[1] https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#Patterns
Usage:
{{#invoke:String|escapePattern|pattern_string}}
Parameters
pattern_string: The pattern string to escape.
]]
function str.escapePattern( frame )
local pattern_str = frame.args[1]
if not pattern_str then
return str._error( 'No pattern string specified' )
end
local result = str._escapePattern( pattern_str )
return result
end
--[[
count
This function counts the number of occurrences of one string in another.
]]
function str.count(frame)
local args = str._getParameters(frame.args, {'source', 'pattern', 'plain'})
local source = args.source or ''
local pattern = args.pattern or ''
local plain = str._getBoolean(args.plain or true)
if plain then
pattern = str._escapePattern(pattern)
end
local _, count = mw.ustring.gsub(source, pattern, '')
return count
end
--[[
endswith
This function determines whether a string ends with another string.
]]
function str.endswith(frame)
local args = str._getParameters(frame.args, {'source', 'pattern'})
local source = args.source or ''
local pattern = args.pattern or ''
if pattern == '' then
-- All strings end with the empty string.
return "yes"
end
if mw.ustring.sub(source, -mw.ustring.len(pattern), -1) == pattern then
return "yes"
else
return ""
end
end
--[[
join
Join all non empty arguments together; the first argument is the separator.
Usage:
{{#invoke:String|join|sep|one|two|three}}
]]
function str.join(frame)
local args = {}
local sep
for _, v in ipairs( frame.args ) do
if sep then
if v ~= '' then
table.insert(args, v)
end
else
sep = v
end
end
return table.concat( args, sep or '' )
end
--[[
Helper function that populates the argument list given that user may need to use a mix of
named and unnamed parameters. This is relevant because named parameters are not
identical to unnamed parameters due to string trimming, and when dealing with strings
we sometimes want to either preserve or remove that whitespace depending on the application.
]]
function str._getParameters( frame_args, arg_list )
local new_args = {}
local index = 1
local value
for _, arg in ipairs( arg_list ) do
value = frame_args[arg]
if value == nil then
value = frame_args[index]
index = index + 1
end
new_args[arg] = value
end
return new_args
end
--[[
Helper function to handle error messages.
]]
function str._error( error_str )
local frame = mw.getCurrentFrame()
local error_category = frame.args.error_category or 'Errors reported by Module String'
local ignore_errors = frame.args.ignore_errors or false
local no_category = frame.args.no_category or false
if str._getBoolean(ignore_errors) then
return ''
end
local error_str = '<strong class="error">String Module Error: ' .. error_str .. '</strong>'
if error_category ~= '' and not str._getBoolean( no_category ) then
error_str = '[[Category:' .. error_category .. ']]' .. error_str
end
return error_str
end
--[[
Helper Function to interpret boolean strings
]]
function str._getBoolean( boolean_str )
local boolean_value
if type( boolean_str ) == 'string' then
boolean_str = boolean_str:lower()
if boolean_str == 'false' or boolean_str == 'no' or boolean_str == '0'
or boolean_str == '' then
boolean_value = false
else
boolean_value = true
end
elseif type( boolean_str ) == 'boolean' then
boolean_value = boolean_str
else
error( 'No boolean value found' )
end
return boolean_value
end
--[[
Helper function that escapes all pattern characters so that they will be treated
as plain text.
]]
function str._escapePattern( pattern_str )
return mw.ustring.gsub( pattern_str, "([%(%)%.%%%+%-%*%?%[%^%$%]])", "%%%1" )
end
return str