Skip to content

Anchors: string start ^ and end $ #420

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

Merged
merged 6 commits into from
Jan 29, 2024
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
An empty string is the only match: it starts and immediately finishes.
Uma string vazia é a única correspondência: Ela começa e imediatamente termina.

The task once again demonstrates that anchors are not characters, but tests.
Esta tarefa demostra novamente que âncoras não são caracteres, mas sim testes.

The string is empty `""`. The engine first matches the `pattern:^` (input start), yes it's there, and then immediately the end `pattern:$`, it's here too. So there's a match.
A string está vazia `""`. O interpretador primeiro encontra o padrão de início da entrada `pattern:^` (que sim, está lá), e então imediatamente o fim da entrada `pattern:$` (que também está). Temos uma correspondência.
4 changes: 2 additions & 2 deletions 9-regular-expressions/04-regexp-anchors/1-start-end/task.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# Regexp ^$
# Expressão Regular ^$

Which string matches the pattern `pattern:^$`?
Qual string corresponde ao padrão `pattern:^$`?
42 changes: 21 additions & 21 deletions 9-regular-expressions/04-regexp-anchors/article.md
Original file line number Diff line number Diff line change
@@ -1,34 +1,34 @@
# Anchors: string start ^ and end $
# Âncoras: início ^ e fim $ de string

The caret `pattern:^` and dollar `pattern:$` characters have special meaning in a regexp. They are called "anchors".
Os caracteres acento circunflexo `pattern:^` e cifrão `pattern:$` possuem um significado especial em expressões regulares. Eles são chamados de "âncoras".

The caret `pattern:^` matches at the beginning of the text, and the dollar `pattern:$` -- at the end.
O acento circunflexo `pattern:^` corresponde ao início da string, e o cifrão `pattern:$` ao final.

For instance, let's test if the text starts with `Mary`:
Neste exemplo, vamos testar se o texto começa com `Maria`:

```js run
let str1 = "Mary had a little lamb";
alert( /^Mary/.test(str1) ); // true
let str1 = "Maria tinha um cordeirinho";
alert( /^Maria/.test(str1) ); // true
```

The pattern `pattern:^Mary` means: "string start and then Mary".
O padrão `pattern:^Maria` quer dizer: "início da string, e então Maria"

Similar to this, we can test if the string ends with `snow` using `pattern:snow$`:
Da mesma maneira, podemos testar se a string termina com `neve` usando `pattern:neve$`:

```js run
let str1 = "its fleece was white as snow";
alert( /snow$/.test(str1) ); // true
let str1 = "Seu velo era branco como a neve";
alert( /neve$/.test(str1) ); // true
```

In these particular cases we could use string methods `startsWith/endsWith` instead. Regular expressions should be used for more complex tests.
Nesses casos em particular, poderíamos usar os métodos do objeto string `startsWith/endsWith` em seu lugar. Expressões regulares devem ser usadas para testes mais complexos.

## Testing for a full match
## Correspondendo com uma string inteira

Both anchors together `pattern:^...$` are often used to test whether or not a string fully matches the pattern. For instance, to check if the user input is in the right format.
Frequentemente, ambas as âncoras `pattern:^...$` são usadas juntas para verificar se uma string inteira corresponde ao padrão. Para confirmar, por exemplo, se a entrada do usuário está no formato correto.

Let's check whether or not a string is a time in `12:34` format. That is: two digits, then a colon, and then another two digits.
Vamos verificar se uma string é um horário no formato `12:34`. Isto é: dois dígitos, seguido de dois pontos (':'), e então mais dois dígitos.

In regular expressions language that's `pattern:\d\d:\d\d`:
Em expressões regulares, isso fica `pattern:\d\d:\d\d`:

```js run
let goodInput = "12:34";
Expand All @@ -39,14 +39,14 @@ alert( regexp.test(goodInput) ); // true
alert( regexp.test(badInput) ); // false
```

Here the match for `pattern:\d\d:\d\d` must start exactly after the beginning of the text `pattern:^`, and the end `pattern:$` must immediately follow.
Nesse exemplo, a correspondência com o padrão `pattern:\d\d:\d\d` deve iniciar exatamente após o início da string `pattern:^`, e ser seguido imediatamente pelo fim da string `pattern:$`.

The whole string must be exactly in this format. If there's any deviation or an extra character, the result is `false`.
A string inteira deve obedecer exatamente a esse formato. Se houver qualquer desvio ou caractere adicional, o resultado será `false`.

Anchors behave differently if flag `pattern:m` is present. We'll see that in the next article.
Âncoras tem um comportamento diferente caso a flag `pattern:m` esteja presente. Veremos isso no próximo artigo.

```smart header="Anchors have \"zero width\""
Anchors `pattern:^` and `pattern:$` are tests. They have zero width.
```smart header="Âncoras tem \"largura zero\""
As âncoras `pattern:^` e `pattern:$` são verificações. Elas não possuem largura.

In other words, they do not match a character, but rather force the regexp engine to check the condition (text start/end).
Em outras palavras, elas não correspondem com um caractere, mas sim com uma posição, obrigando o interpretador regex a verificar a condição de início ou fim da string.
```