From 710518128a82b200a4c4913db584abc81b7f8ed9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=BCnay=20Mert=20Karado=C4=9Fan?= Date: Tue, 21 Jan 2020 19:52:15 +0000 Subject: [PATCH 1/3] Sync with upstream master --- .../01-regexp-introduction/article.md | 168 ++++++++++++------ 9-regular-expressions/index.md | 4 - 2 files changed, 113 insertions(+), 59 deletions(-) diff --git a/9-regular-expressions/01-regexp-introduction/article.md b/9-regular-expressions/01-regexp-introduction/article.md index 57fe02f5d..a35d19a7b 100644 --- a/9-regular-expressions/01-regexp-introduction/article.md +++ b/9-regular-expressions/01-regexp-introduction/article.md @@ -1,51 +1,65 @@ # Patterns and flags +Regular expressions are patterns that provide a powerful way to search and replace in text. + +In JavaScript, they are available via the [RegExp](mdn:js/RegExp) object, as well as being integrated in methods of strings. + +## Regular Expressions + A regular expression (also "regexp", or just "reg") consists of a *pattern* and optional *flags*. -There are two syntaxes to create a regular expression object. +There are two syntaxes that can be used to create a regular expression object. -The long syntax: +The "long" syntax: ```js regexp = new RegExp("pattern", "flags"); ``` -...And the short one, using slashes `"/"`: +And the "short" one, using slashes `"/"`: ```js regexp = /pattern/; // no flags regexp = /pattern/gmi; // with flags g,m and i (to be covered soon) ``` -Slashes `"/"` tell JavaScript that we are creating a regular expression. They play the same role as quotes for strings. +Slashes `pattern:/.../` tell JavaScript that we are creating a regular expression. They play the same role as quotes for strings. -## Usage +In both cases `regexp` becomes an instance of the built-in `RegExp` class. -To search inside a string, we can use method [search](mdn:js/String/search). +The main difference between these two syntaxes is that pattern using slashes `/.../` does not allow for expressions to be inserted (like string template literals with `${...}`). They are fully static. -Here's an example: +Slashes are used when we know the regular expression at the code writing time -- and that's the most common situation. While `new RegExp`, is more often used when we need to create a regexp "on the fly" from a dynamically generated string. For instance: -```js run -let str = "I love JavaScript!"; // will search here +```js +let tag = prompt("What tag do you want to find?", "h2"); -let regexp = /love/; -alert( str.search(regexp) ); // 2 +let regexp = new RegExp(`<${tag}>`); // same as /

/ if answered "h2" in the prompt above ``` -The `str.search` method looks for the pattern `pattern:/love/` and returns the position inside the string. As we might guess, `pattern:/love/` is the simplest possible pattern. What it does is a simple substring search. +## Flags -The code above is the same as: +Regular expressions may have flags that affect the search. -```js run -let str = "I love JavaScript!"; // will search here +There are only 6 of them in JavaScript: -let substr = 'love'; -alert( str.search(substr) ); // 2 -``` +`pattern:i` +: With this flag the search is case-insensitive: no difference between `A` and `a` (see the example below). + +`pattern:g` +: With this flag the search looks for all matches, without it -- only the first match is returned. -So searching for `pattern:/love/` is the same as searching for `"love"`. +`pattern:m` +: Multiline mode (covered in the chapter ). -But that's only for now. Soon we'll create more complex regular expressions with much more searching power. +`pattern:s` +: Enables "dotall" mode, that allows a dot `pattern:.` to match newline character `\n` (covered in the chapter ). + +`pattern:u` +: Enables full unicode support. The flag enables correct processing of surrogate pairs. More about that in the chapter . + +`pattern:y` +: "Sticky" mode: searching at the exact position in the text (covered in the chapter ) ```smart header="Colors" From here on the color scheme is: @@ -55,65 +69,109 @@ From here on the color scheme is: - result -- `match:green` ``` +## Searching: str.match -````smart header="When to use `new RegExp`?" -Normally we use the short syntax `/.../`. But it does not support variable insertions `${...}`. +As mentioned previously, regular expressions are integrated with string methods. -On the other hand, `new RegExp` allows to construct a pattern dynamically from a string, so it's more flexible. +The method `str.match(regexp)` finds all matches of `regexp` in the string `str`. -Here's an example of a dynamically generated regexp: +It has 3 working modes: -```js run -let tag = prompt("Which tag you want to search?", "h2"); -let regexp = new RegExp(`<${tag}>`); +1. If the regular expression has flag `pattern:g`, it returns an array of all matches: + ```js run + let str = "We will, we will rock you"; -// finds

by default -alert( "

".search(regexp)); -``` -```` + alert( str.match(/we/gi) ); // We,we (an array of 2 substrings that match) + ``` + Please note that both `match:We` and `match:we` are found, because flag `pattern:i` makes the regular expression case-insensitive. +2. If there's no such flag it returns only the first match in the form of an array, with the full match at index `0` and some additional details in properties: + ```js run + let str = "We will, we will rock you"; -## Flags + let result = str.match(/we/i); // without flag g -Regular expressions may have flags that affect the search. + alert( result[0] ); // We (1st match) + alert( result.length ); // 1 -There are only 6 of them in JavaScript: + // Details: + alert( result.index ); // 0 (position of the match) + alert( result.input ); // We will, we will rock you (source string) + ``` + The array may have other indexes, besides `0` if a part of the regular expression is enclosed in parentheses. We'll cover that in the chapter . -`i` -: With this flag the search is case-insensitive: no difference between `A` and `a` (see the example below). +3. And, finally, if there are no matches, `null` is returned (doesn't matter if there's flag `pattern:g` or not). -`g` -: With this flag the search looks for all matches, without it -- only the first one (we'll see uses in the next chapter). + This a very important nuance. If there are no matches, we don't receive an empty array, but instead receive `null`. Forgetting about that may lead to errors, e.g.: -`m` -: Multiline mode (covered in the chapter ). + ```js run + let matches = "JavaScript".match(/HTML/); // = null -`s` -: "Dotall" mode, allows `.` to match newlines (covered in the chapter ). + if (!matches.length) { // Error: Cannot read property 'length' of null + alert("Error in the line above"); + } + ``` -`u` -: Enables full unicode support. The flag enables correct processing of surrogate pairs. More about that in the chapter . + If we'd like the result to always be an array, we can write it this way: + + ```js run + let matches = "JavaScript".match(/HTML/)*!* || []*/!*; + + if (!matches.length) { + alert("No matches"); // now it works + } + ``` + +## Replacing: str.replace + +The method `str.replace(regexp, replacement)` replaces matches found using `regexp` in string `str` with `replacement` (all matches if there's flag `pattern:g`, otherwise, only the first one). -`y` -: Sticky mode (covered in the chapter ) +For instance: -We'll cover all these flags further in the tutorial. +```js run +// no flag g +alert( "We will, we will".replace(/we/i, "I") ); // I will, we will + +// with flag g +alert( "We will, we will".replace(/we/ig, "I") ); // I will, I will +``` + +The second argument is the `replacement` string. We can use special character combinations in it to insert fragments of the match: + +| Symbols | Action in the replacement string | +|--------|--------| +|`$&`|inserts the whole match| +|$`|inserts a part of the string before the match| +|`$'`|inserts a part of the string after the match| +|`$n`|if `n` is a 1-2 digit number, then it inserts the contents of n-th parentheses, more about it in the chapter | +|`$`|inserts the contents of the parentheses with the given `name`, more about it in the chapter | +|`$$`|inserts character `$` | -For now, the simplest flag is `i`, here's an example: +An example with `pattern:$&`: ```js run -let str = "I love JavaScript!"; +alert( "I love HTML".replace(/HTML/, "$& and JavaScript") ); // I love HTML and JavaScript +``` + +## Testing: regexp.test -alert( str.search(/LOVE/i) ); // 2 (found lowercased) +The method `regexp.test(str)` looks for at least one match, if found, returns `true`, otherwise `false`. + +```js run +let str = "I love JavaScript"; +let regexp = /LOVE/i; -alert( str.search(/LOVE/) ); // -1 (nothing found without 'i' flag) +alert( regexp.test(str) ); // true ``` -So the `i` flag already makes regular expressions more powerful than a simple substring search. But there's so much more. We'll cover other flags and features in the next chapters. +Later in this chapter we'll study more regular expressions, walk through more examples, and also meet other methods. +Full information about the methods is given in the article . ## Summary -- A regular expression consists of a pattern and optional flags: `g`, `i`, `m`, `u`, `s`, `y`. -- Without flags and special symbols that we'll study later, the search by a regexp is the same as a substring search. -- The method `str.search(regexp)` returns the index where the match is found or `-1` if there's no match. In the next chapter we'll see other methods. +- A regular expression consists of a pattern and optional flags: `pattern:g`, `pattern:i`, `pattern:m`, `pattern:u`, `pattern:s`, `pattern:y`. +- Without flags and special symbols (that we'll study later), the search by a regexp is the same as a substring search. +- The method `str.match(regexp)` looks for matches: all of them if there's `pattern:g` flag, otherwise, only the first one. +- The method `str.replace(regexp, replacement)` replaces matches found using `regexp` with `replacement`: all of them if there's `pattern:g` flag, otherwise only the first one. +- The method `regexp.test(str)` returns `true` if there's at least one match, otherwise, it returns `false`. diff --git a/9-regular-expressions/index.md b/9-regular-expressions/index.md index 7499c584d..ac25aaa67 100644 --- a/9-regular-expressions/index.md +++ b/9-regular-expressions/index.md @@ -1,7 +1,3 @@ # Regular expressions Regular expressions is a powerful way of doing search and replace in strings. - -In JavaScript regular expressions are implemented using objects of a built-in `RegExp` class and integrated with strings. - -Please note that regular expressions vary between programming languages. In this tutorial we concentrate on JavaScript. Of course there's a lot in common, but they are a somewhat different in Perl, Ruby, PHP etc. From 50012c81ea79f7eb39df06e0fe5f1066e00b4021 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=BCnay=20Mert=20Karado=C4=9Fan?= Date: Tue, 21 Jan 2020 20:46:49 +0000 Subject: [PATCH 2/3] Translate Patterns and flags --- .../01-regexp-introduction/article.md | 142 +++++++++--------- 1 file changed, 72 insertions(+), 70 deletions(-) diff --git a/9-regular-expressions/01-regexp-introduction/article.md b/9-regular-expressions/01-regexp-introduction/article.md index a35d19a7b..86c4bc703 100644 --- a/9-regular-expressions/01-regexp-introduction/article.md +++ b/9-regular-expressions/01-regexp-introduction/article.md @@ -1,132 +1,133 @@ -# Patterns and flags +# Kalıplar ve işaretler -Regular expressions are patterns that provide a powerful way to search and replace in text. +Düzenli ifadeler, metinde arama ve değiştirme yapmak için etkili bir yöntem sağlayan kalıplardır. -In JavaScript, they are available via the [RegExp](mdn:js/RegExp) object, as well as being integrated in methods of strings. +JavaScript'te, [RegExp](mdn:js/RegExp) nesnesi aracılığıyla kullanılabilirler ve ayrıca string metotlarına entegre edilmişlerdir. -## Regular Expressions +## Düzenli İfadeler -A regular expression (also "regexp", or just "reg") consists of a *pattern* and optional *flags*. +Bir düzenli ifade ("regexp" veya sadece "reg") bir _kalıp_ ve isteğe bağlı *işaretler*den oluşur. -There are two syntaxes that can be used to create a regular expression object. +Düzenli ifade nesnesi oluşturmak için kullanılabilecek iki sözdizimi vardır. -The "long" syntax: +Uzun olan sözdizimi: ```js -regexp = new RegExp("pattern", "flags"); +regexp = new RegExp("kalıp", "işaretler"); ``` -And the "short" one, using slashes `"/"`: +Ve bölme işareti "/" kullanan kısa olanı: ```js -regexp = /pattern/; // no flags -regexp = /pattern/gmi; // with flags g,m and i (to be covered soon) +regexp = /kalıp/; // işaret yok +regexp = /kalıp/gim; // g, m ve i işaretleriyle birlikte (yakında ele alınacak) ``` -Slashes `pattern:/.../` tell JavaScript that we are creating a regular expression. They play the same role as quotes for strings. +Bölme işaretleri `pattern:/.../` JavaScript'e düzenli bir ifade oluşturduğumuzu söyler. Aynı tırnak işaretlerinin String oluşturduğumuzu söylediği gibi. -In both cases `regexp` becomes an instance of the built-in `RegExp` class. +Her iki durumda da `regexp`, `RegExp` sınıfının bir örneği oluşturulmuş olur. -The main difference between these two syntaxes is that pattern using slashes `/.../` does not allow for expressions to be inserted (like string template literals with `${...}`). They are fully static. +Bu ikisi arasındaki temel fark, bölme işareti `/.../` kullanan modelin kalıba expression eklenmesine izin vermemesidir (`${...}` kullanan string şablonları gibi). Tamamen statiktirler. -Slashes are used when we know the regular expression at the code writing time -- and that's the most common situation. While `new RegExp`, is more often used when we need to create a regexp "on the fly" from a dynamically generated string. For instance: +Bölme işaretleri, kod yazarken düzenli ifadeyi önceden bildiğimizde kullanılır -- ve bu en yaygın durumdur. `new RegExp` ise, dinamik olarak oluşturulan bir string'den anında bir regexp oluşturmamız gerektiğinde daha sık kullanılır. Örneğin: ```js -let tag = prompt("What tag do you want to find?", "h2"); +let tag = prompt("Hangi tag'i bulmak istiyorsun?", "h2"); -let regexp = new RegExp(`<${tag}>`); // same as /

/ if answered "h2" in the prompt above +let regexp = new RegExp(`<${tag}>`); // yukarıdaki prompt'a "h2" cevabı verildiyse, /

/ ile aynı olur. ``` -## Flags +## İşaretler -Regular expressions may have flags that affect the search. +Düzenli ifadelerde aramayı etkileyen işaretler olabilir. -There are only 6 of them in JavaScript: +JavaScript'te bunlardan sadece 6 tanesi var: `pattern:i` -: With this flag the search is case-insensitive: no difference between `A` and `a` (see the example below). +: Bu işaretle arama, büyük/küçük harfe duyarlı değildir: `A` ve `a` arasında fark yoktur (aşağıdaki örneğe bakın). `pattern:g` -: With this flag the search looks for all matches, without it -- only the first match is returned. +: Bu işaretle arama, tüm eşleşenleri arar. Eğer g işareti yoksa, sadece ilk eşleme döndürülür. `pattern:m` -: Multiline mode (covered in the chapter ). +: Çok satırlı mod ( bölümünde ele alınmıştır). `pattern:s` -: Enables "dotall" mode, that allows a dot `pattern:.` to match newline character `\n` (covered in the chapter ). +: Yeni satır karakteri `\n` ile eşleşmek için noktaya `pattern:.` izin veren “dotall” modunu etkinleştirir. ( bölümünde ele alınmıştır). `pattern:u` -: Enables full unicode support. The flag enables correct processing of surrogate pairs. More about that in the chapter . +: Tam unicode desteğini etkinleştirir. Bu işaret, vekil çiftlerin doğru işlenmesini sağlar. Bununla ilgili daha fazla bilgi bölümünde. `pattern:y` -: "Sticky" mode: searching at the exact position in the text (covered in the chapter ) +: “Yapışkan” mod: metindeki tam pozisyonu arar ( bölümünde ele alınmıştır) -```smart header="Colors" -From here on the color scheme is: +```smart header="Renkler" +Buradan itibaren renk şeması şu şekilde olacak: - regexp -- `pattern:red` -- string (where we search) -- `subject:blue` -- result -- `match:green` +- string (aradığımız yer) -- `subject:blue` +- sonuç -- `match:green` ``` -## Searching: str.match +## Arama: str.match -As mentioned previously, regular expressions are integrated with string methods. +Daha önce de belirtildiği gibi, düzenli ifadeler string metotlarına entegre edilmiştir. -The method `str.match(regexp)` finds all matches of `regexp` in the string `str`. +`str.match(regexp)` metodu `regexp` ile `str` stringindeki tüm eşleşmeleri bulur. -It has 3 working modes: +3 çalışma modu vardır: + +1. Düzenli ifadede `pattern:g` işareti varsa, tüm eşleşmelerden oluşan bir dizi döndürür: -1. If the regular expression has flag `pattern:g`, it returns an array of all matches: ```js run let str = "We will, we will rock you"; - alert( str.match(/we/gi) ); // We,we (an array of 2 substrings that match) + alert( str.match(/we/gi) ); // We,we (eşleşen 2 string'den oluşan bir dizi) ``` - Please note that both `match:We` and `match:we` are found, because flag `pattern:i` makes the regular expression case-insensitive. + Hem `match:We` hem de `match:we`'nin bulunduğuna dikkat edin, çünkü `pattern:i` işareti aramayı büyük/küçük harfe duyarsız hale getirir. -2. If there's no such flag it returns only the first match in the form of an array, with the full match at index `0` and some additional details in properties: +2. Eğer `pattern:g` işareti yoksa, yalnızca ilk eşleşmeyi döndürür. Dönen ifade bir dizi formundadır. İlk eşleşme dizininin `0` indeksinde yer alır ve dizinin bazı ek ayrıntılar sağlayan property'leri vardır: ```js run let str = "We will, we will rock you"; - let result = str.match(/we/i); // without flag g + let result = str.match(/we/i); // g işareti olmadan - alert( result[0] ); // We (1st match) + alert( result[0] ); // We (ilk eşleşme) alert( result.length ); // 1 // Details: - alert( result.index ); // 0 (position of the match) - alert( result.input ); // We will, we will rock you (source string) + alert( result.index ); // 0 (eşlemenin string'deki pozisyonu) + alert( result.input ); // We will, we will rock you (kaynak string) ``` - The array may have other indexes, besides `0` if a part of the regular expression is enclosed in parentheses. We'll cover that in the chapter . + Düzenli ifadenin bir kısmı parantez içine alınmışsa dizinin `0` dışında başka indeksleri de olabilir. Bunu, bölümünde ele alacağız. -3. And, finally, if there are no matches, `null` is returned (doesn't matter if there's flag `pattern:g` or not). +3. Son olarak, eşleşme yoksa `null` döndürülür (`pattern:g` işareti olup olmadığı önemli değildir). - This a very important nuance. If there are no matches, we don't receive an empty array, but instead receive `null`. Forgetting about that may lead to errors, e.g.: + Bu çok önemli bir nüans. Eşleşme yoksa boş bir dizi almıyoruz, bunun yerine `null` alıyoruz. Bunu unutmak hatalara neden olabilir, örneğin: ```js run let matches = "JavaScript".match(/HTML/); // = null if (!matches.length) { // Error: Cannot read property 'length' of null - alert("Error in the line above"); + alert("Yukardaki satırda hata var"); } ``` - If we'd like the result to always be an array, we can write it this way: + Sonucun her zaman bir dizi olmasını istiyorsak, bunu şu şekilde yazabiliriz: ```js run let matches = "JavaScript".match(/HTML/)*!* || []*/!*; if (!matches.length) { - alert("No matches"); // now it works + alert("Eşleşme yok"); // şimdi çalışıyor } ``` -## Replacing: str.replace +## Yer değiştirme: str.replace -The method `str.replace(regexp, replacement)` replaces matches found using `regexp` in string `str` with `replacement` (all matches if there's flag `pattern:g`, otherwise, only the first one). +`str.replace(regexp, yeni_str)` metodu, string `str`'de `regexp` kullanılarak bulunan eşleşmeleri `yeni_str` ile değiştirir (`pattern:g` işareti varsa tüm eşleşmeler, aksi takdirde yalnızca ilk olanı). -For instance: +Örneğin: ```js run // no flag g @@ -136,26 +137,27 @@ alert( "We will, we will".replace(/we/i, "I") ); // I will, we will alert( "We will, we will".replace(/we/ig, "I") ); // I will, I will ``` -The second argument is the `replacement` string. We can use special character combinations in it to insert fragments of the match: +İkinci argüman, `yeni_str` bulunan eşlemenin yerine geçen string'dir. Eşleşmenin parçalarını eklemek için özel karakter kombinasyonları kullanabiliriz: -| Symbols | Action in the replacement string | +| Semboller | Değiştirilen yeni_str'de yapılan eylem | |--------|--------| -|`$&`|inserts the whole match| -|$`|inserts a part of the string before the match| -|`$'`|inserts a part of the string after the match| -|`$n`|if `n` is a 1-2 digit number, then it inserts the contents of n-th parentheses, more about it in the chapter | -|`$`|inserts the contents of the parentheses with the given `name`, more about it in the chapter | -|`$$`|inserts character `$` | +|`$&`|tüm eşleşmeyi ekler| +|$`|string'in eşleşmeden önce gelen kısmını ekler| +|`$'`|string'in eşleşmeden sonra gelen kısmını ekler| +|`$n`|`n` 1-2 basamaklı bir sayıysa, n. parantezlerin içeriğini ekler, bununla ilgili daha fazla bilgi bölümünde| +|`$`|`isim` adı verilen parantezlerin içeriğini ekler, daha fazlası bölümünde| +|`$$`|`$` karakterini ekler| -An example with `pattern:$&`: +`pattern:$&` ile bir örnek:: ```js run alert( "I love HTML".replace(/HTML/, "$& and JavaScript") ); // I love HTML and JavaScript ``` -## Testing: regexp.test +## Test: regexp.test + +`regexp.test(str)` metodu en az bir eşleşme arar, eşleşme bulunursa `true` değerini döndürür, aksi takdirde `false` değerini döndürür. -The method `regexp.test(str)` looks for at least one match, if found, returns `true`, otherwise `false`. ```js run let str = "I love JavaScript"; @@ -164,14 +166,14 @@ let regexp = /LOVE/i; alert( regexp.test(str) ); // true ``` -Later in this chapter we'll study more regular expressions, walk through more examples, and also meet other methods. +Bu bölümün ilerleyen kısımlarında düzenli ifadeler üzerinde daha fazla çalışacağız, daha fazla örnek üzerinde duracağız ve diğer metotlarla da karşılaşacağız. -Full information about the methods is given in the article . +Metotlar hakkında tam bilgi makalesinde verilmiştir. -## Summary +## Özet -- A regular expression consists of a pattern and optional flags: `pattern:g`, `pattern:i`, `pattern:m`, `pattern:u`, `pattern:s`, `pattern:y`. -- Without flags and special symbols (that we'll study later), the search by a regexp is the same as a substring search. -- The method `str.match(regexp)` looks for matches: all of them if there's `pattern:g` flag, otherwise, only the first one. -- The method `str.replace(regexp, replacement)` replaces matches found using `regexp` with `replacement`: all of them if there's `pattern:g` flag, otherwise only the first one. -- The method `regexp.test(str)` returns `true` if there's at least one match, otherwise, it returns `false`. +- Düzenli ifade bir kalıp ve isteğe bağlı işaretlerden oluşur: `pattern:g`, `pattern:i`, `pattern:m`, `pattern:u`, `pattern:s`, `pattern:y`. +- İşaretler ve özel semboller olmadan (daha sonra inceleyeceğiz) düzenli ifadelerle arama bir substring aramasıyla aynıdır. +- `str.match(regexp)` metodu eşleşmeleri arar: `pattern:g` işareti varsa tümü, aksi takdirde yalnızca birincisini döner. +- `str.replace(regexp, yeni_str)` metodu, `regexp` kullanılarak bulunan eşleşmeleri `yeni_str` ile değiştirir: `pattern:g` işareti varsa tümünü, aksi takdirde yalnızca ilkini değiştirir. +- `regexp.test(str)` metodu en az bir eşleşme varsa `true` değerini döndürür, aksi takdirde `false` değerini döndürür. From 38c576fe1086da3068a75534ab225cc5c340f591 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=BCnay=20Mert=20Karado=C4=9Fan?= Date: Tue, 21 Jan 2020 20:51:24 +0000 Subject: [PATCH 3/3] Translate Regular expressions index --- 9-regular-expressions/index.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/9-regular-expressions/index.md b/9-regular-expressions/index.md index ac25aaa67..c0515aa19 100644 --- a/9-regular-expressions/index.md +++ b/9-regular-expressions/index.md @@ -1,3 +1,3 @@ -# Regular expressions +# Düzenli İfadeler -Regular expressions is a powerful way of doing search and replace in strings. +Düzenli ifadeler, dizelerde arama ve değiştirme yapmanın etkili bir yoludur.