| 1 |
--- |
| 2 |
title: strings.FindRESubmatch |
| 3 |
description: Returns a slice of all successive matches of the regular expression. Each element is a slice of strings holding the text of the leftmost match of the regular expression and the matches, if any, of its subexpressions. |
| 4 |
categories: [] |
| 5 |
keywords: [] |
| 6 |
params: |
| 7 |
functions_and_methods: |
| 8 |
aliases: [findRESubmatch] |
| 9 |
returnType: '[][]string' |
| 10 |
signatures: ['strings.FindRESubmatch PATTERN INPUT [LIMIT]'] |
| 11 |
aliases: [/functions/findresubmatch] |
| 12 |
--- |
| 13 |
|
| 14 |
By default, `findRESubmatch` finds all matches. You can limit the number of matches with an optional LIMIT argument. A return value of nil indicates no match. |
| 15 |
|
| 16 |
{{% include "/_common/functions/regular-expressions.md" %}} |
| 17 |
|
| 18 |
## Demonstrative examples |
| 19 |
|
| 20 |
```go-html-template |
| 21 |
{{ findRESubmatch `a(x*)b` "-ab-" }} → [["ab" ""]] |
| 22 |
{{ findRESubmatch `a(x*)b` "-axxb-" }} → [["axxb" "xx"]] |
| 23 |
{{ findRESubmatch `a(x*)b` "-ab-axb-" }} → [["ab" ""] ["axb" "x"]] |
| 24 |
{{ findRESubmatch `a(x*)b` "-axxb-ab-" }} → [["axxb" "xx"] ["ab" ""]] |
| 25 |
{{ findRESubmatch `a(x*)b` "-axxb-ab-" 1 }} → [["axxb" "xx"]] |
| 26 |
``` |
| 27 |
|
| 28 |
## Practical example |
| 29 |
|
| 30 |
This Markdown: |
| 31 |
|
| 32 |
```md |
| 33 |
- [Example](https://example.org) |
| 34 |
- [Hugo](https://gohugo.io) |
| 35 |
``` |
| 36 |
|
| 37 |
Produces this HTML: |
| 38 |
|
| 39 |
```html |
| 40 |
<ul> |
| 41 |
<li><a href="https://example.org">Example</a></li> |
| 42 |
<li><a href="https://gohugo.io">Hugo</a></li> |
| 43 |
</ul> |
| 44 |
``` |
| 45 |
|
| 46 |
To match the anchor elements, capturing the link destination and text: |
| 47 |
|
| 48 |
```go-html-template |
| 49 |
{{ $regex := `<a\s*href="(.+?)">(.+?)</a>` }} |
| 50 |
{{ $matches := findRESubmatch $regex .Content }} |
| 51 |
``` |
| 52 |
|
| 53 |
Viewed as JSON, the data structure of `$matches` in the code above is: |
| 54 |
|
| 55 |
```json |
| 56 |
[ |
| 57 |
[ |
| 58 |
"<a href=\"https://example.org\"></a>Example</a>", |
| 59 |
"https://example.org", |
| 60 |
"Example" |
| 61 |
], |
| 62 |
[ |
| 63 |
"<a href=\"https://gohugo.io\">Hugo</a>", |
| 64 |
"https://gohugo.io", |
| 65 |
"Hugo" |
| 66 |
] |
| 67 |
] |
| 68 |
``` |
| 69 |
|
| 70 |
To render the `href` attributes: |
| 71 |
|
| 72 |
```go-html-template |
| 73 |
{{ range $matches }} |
| 74 |
{{ index . 1 }} |
| 75 |
{{ end }} |
| 76 |
``` |
| 77 |
|
| 78 |
Result: |
| 79 |
|
| 80 |
```text |
| 81 |
https://example.org |
| 82 |
https://gohugo.io |
| 83 |
``` |
| 84 |
|
| 85 |
> [!NOTE] |
| 86 |
> You can write and test your regular expression using [regex101.com][]. Be sure to select the Go flavor before you begin. |
| 87 |
|
| 88 |
[regex101.com]: https://regex101.com/ |