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

find और match से Text खोजना

find एक pattern locate करता है और match वह piece निकालता है जो आपने माँगा था।

find और match से Text ढूंढना

string.find(s, pattern, init, plain) पहले match की start और end positions return करता है, या nil। plain argument को true set करने पर यह एक pattern की बजाय literal text search करता है। string.match matched text return करता है, या अगर pattern में parentheses हों तो captures। Lua patterns regular expressions से simpler हैं और digits के लिए %d, letters के लिए %a, और whitespace के लिए %s इस्तेमाल करते हैं।

Note: एक pattern में . और % जैसे special characters को एक percent sign से escape करना ज़रूरी है।

उदाहरण: Finding text with find and match

lua
local s = "order 66 shipped"
print(s:find("66"))
print(s:find("(%d+)"))
print(s:match("%d+"))
print(s:match("(%a+) (%d+)"))
print(("a.b"):find(".", 1, true))
print(s:find("xyz"))

-- Output:
-- 7	8
-- 7	8	66
-- 66
-- order	66
-- 2	2
-- nil
{# 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. यह मान लेना कि Lua patterns पूरी regular expressions हैं
  2. escape करने के लिए percent sign की बजाय backslash इस्तेमाल करना
  3. यह भूल जाना कि find positions return करता है, text नहीं
चैप्टर सारांश
  • find start और end indexes return करता है
  • match matched text या captures return करता है
  • %d %a %s character classes हैं
  • plain search के लिए find को true pass करें

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.