← Back to Lua Course | Chapter 3: Strings | Lesson 5 of 7

Captures और gmatch

gmatch एक string में एक pattern के हर match पर loop करता है।

In this page:

  1. Captures और gmatch

Captures और gmatch

string.gmatch एक iterator return करता है जो बारी-बारी हर match, या captures का हर set, yield करता है। एक pattern में parentheses captures define करती हैं, और quantifiers *, +, -, और ? हैं। Common uses एक string को words में split करना या key=value pairs पढ़ना हैं।

Note: Pattern [^,]+ characters के किसी भी run से match करता है जो commas नहीं हैं, जो splitting के लिए handy है।

उदाहरण: Captures and gmatch

lua
for word in ("one two  three"):gmatch("%a+") do
  print(word)
end
for k, v in ("a=1, b=2"):gmatch("(%w+)=(%w+)") do
  print(k, v)
end
local fields = {}
for f in ("x,y,,z"):gmatch("[^,]+") do fields[#fields + 1] = f end
print(#fields, table.concat(fields, "|"))

-- Output:
-- one
-- two
-- three
-- a	1
-- b	2
-- 3	x|y|z
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. gmatch को एक for loop में इस्तेमाल किए बिना call करना
  2. lazy quantifier - को एक range से confuse करना
  3. जब आपको captures चाहिए तो parentheses भूल जाना
चैप्टर सारांश
  • gmatch matches पर एक iterator देता है
  • Parentheses captures बनाते हैं
  • * + - ? quantifiers हैं
  • [^x]+ x के बिना एक run से match करता है

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.