Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add docs for empty captures in string patterns #835

Merged
merged 6 commits into from
Sep 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions content/en-us/luau/strings.md
Original file line number Diff line number Diff line change
Expand Up @@ -549,3 +549,41 @@ the following:
</tr>
</tbody>
</table>

In addition to all of the above, there is a special case with an **empty capture** (`()`). If a capture is empty, then the position in the string will be captured:

```lua
local match1 = "Where does the capture happen? Who knows!"
local match2 = "This string is longer than the first one. Where does the capture happen? Who knows?!"

local pattern = "()Where does the capture happen%? Who knows!()"

local start1, finish1 = string.match(match1, pattern)
print(start1, finish1) --> 1 42

local start2, finish2 = string.match(match2, pattern)
print(start2, finish2) --> 43 84
```

These special captures may be nested like normal ones:

```lua
local places = "The Cloud Kingdom is heavenly, The Forest Kingdom is peaceful."
local pattern = "The (%a+()) Kingdom is %a+"

for kingdom, position in string.gmatch(places, pattern) do
print(kingdom, position)
end
--> Cloud 10
--> Forest 42
```

The returned values are unusual in that they are **numbers** rather than strings:

```lua
local match = "This is an example"
local pattern = "This is an ()example"

local position = string.match(match, pattern)
print(typeof(position)) --> number
```
Loading