Skip to content

Commit

Permalink
Add docs for empty captures in string patterns (#835)
Browse files Browse the repository at this point in the history
## Changes

This adds documentation for empty captures in string patterns, as they
behave specially and are not currently documented.

It notes their behavior and demonstrates how they can be used.

## Checks

By submitting your pull request for review, you agree to the following:

- [x] This contribution was created in whole or in part by me, and I
have the right to submit it under the terms of this repository's open
source licenses.
- [x] I understand and agree that this contribution and a record of it
are public, maintained indefinitely, and may be redistributed under the
terms of this repository's open source licenses.
- [x] To the best of my knowledge, all proposed changes are accurate.

---------
  • Loading branch information
Dekkonot authored Sep 24, 2024
1 parent 87934a9 commit 6d7d44b
Showing 1 changed file with 38 additions and 0 deletions.
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
```

0 comments on commit 6d7d44b

Please sign in to comment.