diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
new file mode 100644
index 00000000..f5160b29
--- /dev/null
+++ b/.github/FUNDING.yml
@@ -0,0 +1,3 @@
+# These are supported funding model platforms
+
+github: [ziishaned]
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..0f971a30
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+.vscode
+.DS_STORE
\ No newline at end of file
diff --git a/LICENSE b/LICENSE.md
similarity index 96%
rename from LICENSE
rename to LICENSE.md
index 78bf0689..5171fedf 100644
--- a/LICENSE
+++ b/LICENSE.md
@@ -1,6 +1,6 @@
MIT License
-Copyright (c) 2017 Zeeshan Ahmed
+Copyright (c) 2019 Zeeshan Ahmad
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
diff --git a/README.md b/README.md
index 5627cfa5..d27e8387 100644
--- a/README.md
+++ b/README.md
@@ -1,67 +1,98 @@
-
-
-
+
+
+
+
-
+
"the" => The fat cat sat on the mat. @@ -69,9 +100,11 @@ A regular expression is just a pattern of characters that we use to perform sear [Test the regular expression](https://regex101.com/r/dmRygT/1) -The regular expression `123` matches the string `123`. The regular expression is matched against an input string by comparing each -character in the regular expression to each character in the input string, one after another. Regular expressions are normally -case-sensitive so the regular expression `The` would not match the string `the`. +The regular expression `123` matches the string `123`. The regular expression is +matched against an input string by comparing each character in the regular +expression to each character in the input string, one after another. Regular +expressions are normally case-sensitive so the regular expression `The` would +not match the string `the`.+ +[Test the regular expression](https://regex101.com/r/8Efx5G/1) + +## 5. 플래그 + +플래그는 정규표현식의 출력값을 수정하기 때문에 수정자(modifier)라고도 불린다. 이러한 플래그들은 어떤 순서 혹은 조합으로 사용 가능하며 정규 표현식의 일부분이다. + +|플래그|설명| +|:----:|----| +|i|대소문자 구분없음: 매칭이 대소문자를 구분하지 않도록 설정.| +|g|전체 검색: 입력 문자열 전체를 대상으로 패턴을 검색.| +|m|멀티 라인: 앵터 메타 문자가 각 줄마다 동작하도록 설정.| + +### 5.1 대소문자 구분없음 + +수정자 `i`는 대소문자 구분없는 매칭을 수행하는데 사용된다. 예를 들어, 정규 표현식 `/The/gi`는 대문자 `T`, 소문자 `h`, 소문자 `e`가 차례로 나오는 패턴을 의미한다. 여기서 정규 표현식 마지막에 있는 `i` 플래그가 정규 표현식 엔진에게 대소문자를 구분하지 않도록 알려준다. `g` 플래그는 전체 입력 문자열 내부에서 패턴을 검색하기 위해 설정되었다. + +"The" => The fat cat sat on the mat. @@ -81,9 +114,10 @@ case-sensitive so the regular expression `The` would not match the string `the`. ## 2. Meta Characters -Meta characters are the building blocks of the regular expressions. Meta characters do not stand for themselves but instead are -interpreted in some special way. Some meta characters have a special meaning and are written inside square brackets. -The meta characters are as follows: +Meta characters are the building blocks of regular expressions. Meta +characters do not stand for themselves but instead are interpreted in some +special way. Some meta characters have a special meaning and are written inside +square brackets. The meta characters are as follows: |Meta character|Description| |:----:|----| @@ -91,7 +125,7 @@ The meta characters are as follows: |[ ]|Character class. Matches any character contained between the square brackets.| |[^ ]|Negated character class. Matches any character that is not contained between the square brackets| |*|Matches 0 or more repetitions of the preceding symbol.| -|+|Matches 1 or more repetitions of the preceding symbol. +|+|Matches 1 or more repetitions of the preceding symbol.| |?|Makes the preceding symbol optional.| |{n,m}|Braces. Matches at least "n" but not more than "m" repetitions of the preceding symbol.| |(xyz)|Character group. Matches the characters xyz in that exact order.| @@ -100,11 +134,12 @@ The meta characters are as follows: |^|Matches the beginning of the input.| |$|Matches the end of the input.| -## 2.1 Full stop +## 2.1 The Full Stop -Full stop `.` is the simplest example of meta character. The meta character `.` matches any single character. It will not match return -or newline characters. For example, the regular expression `.ar` means: any character, followed by the letter `a`, followed by the -letter `r`. +The full stop `.` is the simplest example of a meta character. The meta character `.` +matches any single character. It will not match return or newline characters. +For example, the regular expression `.ar` means: any character, followed by the +letter `a`, followed by the letter `r`.+ +[Verifica l'espressione regolare](https://regex101.com/r/8Efx5G/1) + +## 5. Opzioni + +Le opzioni (o modificatori) modificano il risultato delle espressioni regolari. Queste opzioni possono essere utilizzate in qualsiasi ordine o combinazione, sono parti integranti di RegExp. + +|Opzione|Descrizione| +|:----:|----| +|i|Non sensibilità maiuscolo / minuscolo| +|g|Ricerca globale: trova tutte le corrispondenze, non solo la prima.| +|m|Multi riga: estende il funzionamento delle ancore su ogni riga.| + +### 5.1 Non sensibilità maiuscolo / minuscolo + +L'opzione `i` è usato per rendere la corrispondenza non sensibile a maiuscolo / minuscolo. Ad esempio, l'espressione regolare `/The/gi` corrisponde a: una lettera maiuscola `T`, seguita da una lettera minuscola `h`, seguita da una lettera minuscola `e`. L'opzione `i` alla fine dell'espressione regolare indica di ignorare minuscole / maiuscole. Come si può notare, l'utilizzo dell'opzione `g` estende la ricerca all'intero testo. + +".ar" => The car parked in the garage. @@ -112,11 +147,13 @@ letter `r`. [Test the regular expression](https://regex101.com/r/xc9GkU/1) -## 2.2 Character set +## 2.2 Character Sets -Character sets are also called character class. Square brackets are used to specify character sets. Use a hyphen inside a character set to -specify the characters' range. The order of the character range inside square brackets doesn't matter. For example, the regular -expression `[Tt]he` means: an uppercase `T` or lowercase `t`, followed by the letter `h`, followed by the letter `e`. +Character sets are also called character classes. Square brackets are used to +specify character sets. Use a hyphen inside a character set to specify the +characters' range. The order of the character range inside the square brackets +doesn't matter. For example, the regular expression `[Tt]he` means: an uppercase +`T` or lowercase `t`, followed by the letter `h`, followed by the letter `e`.+ +[Verifica l'espressione regolare](https://regex101.com/r/IDDARt/1) + +### 4.2 Lookahead negativo + +Lookahead negativo è utilizzato per ottenere corrispondenza con una stringa che non è seguita da un determinato schema. Il lookahead negativo è scritto nello stesso modo del lookahead positivo. L'unica differenza consiste nell'utilizzo del carattere di punto esclamativo `!`, al posto del segno uguale `=`, per indicare la negazione, ad esempio `(?!...)`. Vediamo la seguente espressioni regolare `(T|t)he(?!\sfat)` che trova corrispondenza con: tutte le parole `The` o `the` che non sono seguite da uno spazio dalla parola `fat`. + +"[Tt]he" => The car parked in the garage. @@ -124,7 +161,9 @@ expression `[Tt]he` means: an uppercase `T` or lowercase `t`, followed by the le [Test the regular expression](https://regex101.com/r/2ITLQ4/1) -A period inside a character set, however, means a literal period. The regular expression `ar[.]` means: a lowercase character `a`, followed by letter `r`, followed by a period `.` character. +A period inside a character set, however, means a literal period. The regular +expression `ar[.]` means: a lowercase character `a`, followed by the letter `r`, +followed by a period `.` character.+ +[Test the regular expression](https://regex101.com/r/8Efx5G/1) + +## 5. Bendera + +Bendera juga disebut pengubah karena mereka memodifikasi output dari regular +ekspresi. Bendera ini dapat digunakan dalam urutan atau kombinasi apa pun, dan merupakan +bagian integral dari RegExp. + +|Bendera|Deskripsi| +|:----:|----| +|i|Tidak peka huruf besar/kecil: Pencocokan tidak peka huruf besar/kecil.| +|g|Penelusuran Global: Cocokkan semua instance, bukan hanya yang pertama.| +|m|Multiline: Karakter meta jangkar bekerja di setiap baris.| + +### 5.1 Tidak peka huruf besar/kecil + +Pengubah `i` digunakan untuk melakukan pencocokan case-insensitive. Misalnya, +ekspresi reguler `/The/gi` berarti: huruf besar `T`, diikuti dengan huruf kecil +`h`, diikuti oleh `e`. Dan di akhir ekspresi reguler +flag `i` memberitahu mesin ekspresi reguler untuk mengabaikan kasus ini. Sebisa kamu +lihat, kami juga menyediakan flag `g` karena kami ingin mencari pola di +seluruh string masukan. + +"ar[.]" => A garage is a good place to park a car. @@ -132,11 +171,12 @@ A period inside a character set, however, means a literal period. The regular ex [Test the regular expression](https://regex101.com/r/wL3xtE/1) -### 2.2.1 Negated character set +### 2.2.1 Negated Character Sets -In general, the caret symbol represents the start of the string, but when it is typed after the opening square bracket it negates the -character set. For example, the regular expression `[^c]ar` means: any character except `c`, followed by the character `a`, followed by -the letter `r`. +In general, the caret symbol represents the start of the string, but when it is +typed after the opening square bracket it negates the character set. For +example, the regular expression `[^c]ar` means: any character except `c`, +followed by the character `a`, followed by the letter `r`.+ +[Uji ekspresi reguler](https://regex101.com/r/IDDARt/1) + +### 4.2 Pandangan ke Depan Negatif + +Pandangan negatif ke depan digunakan ketika kita perlu mendapatkan semua kecocokan dari string input +yang tidak mengikuti pola tertentu. Sebuah lookahead negatif ditulis dengan cara yang sama seperti a +pandangan positif ke depan. Satu-satunya perbedaan adalah, alih-alih tanda sama dengan `=`, kami +gunakan tanda seru `!` untuk menunjukkan negasi yaitu `(?!...)`. Yuk simak berikut ini +ekspresi reguler `(T|t)he(?!\sfat)` yang artinya: dapatkan semua kata `The` atau `the` +dari string input yang tidak diikuti oleh karakter spasi dan kata `fat`. + +"[^c]ar" => The car parked in the garage. @@ -146,14 +186,17 @@ the letter `r`. ## 2.3 Repetitions -Following meta characters `+`, `*` or `?` are used to specify how many times a subpattern can occur. These meta characters act -differently in different situations. +The meta characters `+`, `*` or `?` are used to specify how many times a +subpattern can occur. These meta characters act differently in different +situations. ### 2.3.1 The Star -The symbol `*` matches zero or more repetitions of the preceding matcher. The regular expression `a*` means: zero or more repetitions -of preceding lowercase character `a`. But if it appears after a character set or class then it finds the repetitions of the whole -character set. For example, the regular expression `[a-z]*` means: any number of lowercase letters in a row. +The `*` symbol matches zero or more repetitions of the preceding matcher. The +regular expression `a*` means: zero or more repetitions of the preceding lowercase +character `a`. But if it appears after a character set or class then it finds +the repetitions of the whole character set. For example, the regular expression +`[a-z]*` means: any number of lowercase letters in a row.+ +[Teszteld a reguláris kifejezést](https://regex101.com/r/8Efx5G/1) + +## 5. Flag-ek + +A flag-eket módosítónak hívják, mert módosítják a reguláris kifejezés +kimenetét. Ezeket a flag-eket bármilyen sorban vagy kombinációban lehet +használni, a RegExp szerves részét képezik. + +|Flag|Leírás| +|:----:|----| +|i|Kis-nagybetű érzéketlen: Beállítja, hogy az illeszkedés kis-nagybetű érzéketlen legyen.| +|g|Globális keresés: A bemeneti szövegben mindenütt keresi az illeszkedéseket.| +|m|Többsoros: A horgonyok az összes sorra működnek.| + +### 5.1 Kis-nagybetű érzéketlen + +Az `i` módosító beállítja, hogy az illeszkedés ne legyen kis-nagybetű érzékeny. +Például a `/The/gi` kifejezés jelentése: nagybetűs `T` amit kisbetűs `h`, majd `e` +követ. A kifejezés végén az `i` megmondja a reguláris kifejezés motornak, hogy +hagyja figyelmen kívül a betűk méretét. Ahogy látod, megadtuk a `g` flag-et, mert +az egész bemeneti szövegben akarjuk keresni az illeszkedéseket. + +"[a-z]*" => The car parked in the garage #21. @@ -161,21 +204,25 @@ character set. For example, the regular expression `[a-z]*` means: any number of [Test the regular expression](https://regex101.com/r/7m8me5/1) -The `*` symbol can be used with the meta character `.` to match any string of characters `.*`. The `*` symbol can be used with the -whitespace character `\s` to match a string of whitespace characters. For example, the expression `\s*cat\s*` means: zero or more -spaces, followed by lowercase character `c`, followed by lowercase character `a`, followed by lowercase character `t`, followed by -zero or more spaces. +The `*` symbol can be used with the meta character `.` to match any string of +characters `.*`. The `*` symbol can be used with the whitespace character `\s` +to match a string of whitespace characters. For example, the expression +`\s*cat\s*` means: zero or more spaces, followed by a lowercase `c`, +followed by a lowercase `a`, followed by a lowercase `t`, +followed by zero or more spaces.+ +[Teszteld a reguláris kifejezést](https://regex101.com/r/IDDARt/1) + +### 4.2 Negative Lookahead + +A negatív előrenézést akkor használjuk, ha az olyan illeszkedések kellenek, +amelyeket nem követ egy bizonyos minta. A negatív előrenézést ugyanúgy +definiáljuk mint a pozitív előrenézést, az egyetlen különbség, hogy az +egyenlőségjel `=` helyett negálást `!` használunk: `(?!...)`. Nézzük meg +a következő kifejezést: `(T|t)he(?!\sfat)`, jelentése: szedd ki az összes +`The` vagy `the` szót, amelyeket nem követ a `fat` szó (amit még megelőz +egy szóköz). + +-"\s*cat\s*" => The fat cat sat on the concatenation. +"\s*cat\s*" => The fat cat sat on the concatenation.[Test the regular expression](https://regex101.com/r/gGrwuz/1) ### 2.3.2 The Plus -The symbol `+` matches one or more repetitions of the preceding character. For example, the regular expression `c.+t` means: lowercase -letter `c`, followed by at least one character, followed by the lowercase character `t`. +The `+` symbol matches one or more repetitions of the preceding character. For +example, the regular expression `c.+t` means: a lowercase `c`, followed by +at least one character, followed by a lowercase `t`. It needs to be +clarified that`t` is the last `t` in the sentence."c.+t" => The fat cat sat on the mat. @@ -185,9 +232,10 @@ letter `c`, followed by at least one character, followed by the lowercase charac ### 2.3.3 The Question Mark -In regular expression the meta character `?` makes the preceding character optional. This symbol matches zero or one instance of -the preceding character. For example, the regular expression `[T]?he` means: Optional the uppercase letter `T`, followed by the lowercase -character `h`, followed by the lowercase character `e`. +In regular expressions, the meta character `?` makes the preceding character +optional. This symbol matches zero or one instance of the preceding character. +For example, the regular expression `[T]?he` means: Optional uppercase +`T`, followed by a lowercase `h`, followed by a lowercase `e`.+ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/8Efx5G/1) + +## 5. Σημαίες + +Οι σημαίες καλούνται αλλιώς και τροποποιητές αφού επηρεάζουν τον τρόπο αναζήτησης των +κανονικών εκφράσεων. Μπορούν να χρησιμοποιηθούν με οποιαδήποτε σειρά και σε οποιονδήποτε συνδυασμό +συμβόλων και είναι αναπόσπαστο κομμάτι των RegExp. + +|Σημαία|Περιγραφή| +|:----:|----| +|i|Αλλάζει την αναζήτηση ώστε να μην ενδιαφέρεται για τον αν τα γράμματα είναι πεζά ή κεφαλαία.| +|g|Καθολική αναζήτηση: Ψάχνει ένα μοτίβο σε ολόκληρο το string εισόδου.| +|m|Πολλαπλές γραμμές: Οι μεταχαρακτήρες άγκυρας λειτουργούν σε όλες τις γραμμές.| + +### 5.1 Χωρίς Διάκριση Πεζών-Κεφαλαίων + +Ο τροποποιητής `i` χρησιμοποιείται για αναζήτηση που δεν κάνει διακρίσεις μεταξύ πεζών +και κεφαλαίων γραμμάτων. Για παράδειγμα, η κανονική έκφραση `/The/gi` αναπαριστά: ένα +κεφαλαίο γράμμα `T`, που ακολουθείται από έναν πεζό χαρακτήρα `h`, που ακολουθείται από τον χαρακτήρα `e`. +Στο τέλος της κανονικής έκφρασης υπάρχει η σημαία `i` η οποία λέει στην κανονική +έκφραση να αγνοήσει το αν ένας χαρακτήρας είναι πεζός ή κεφαλαίος. Όπως βλέπετε υπάρχει και η +σημαία `g` ώστε η αναζήτηση του μοτίβου να γίνει σε όλο το string εισόδου. + +"[T]he" => The car is parked in the garage. @@ -203,9 +251,10 @@ character `h`, followed by the lowercase character `e`. ## 2.4 Braces -In regular expression braces that are also called quantifiers are used to specify the number of times that a -character or a group of characters can be repeated. For example, the regular expression `[0-9]{2,3}` means: Match at least 2 digits but not more than 3 ( -characters in the range of 0 to 9). +In regular expressions, braces (also called quantifiers) are used to +specify the number of times that a character or a group of characters can be +repeated. For example, the regular expression `[0-9]{2,3}` means: Match at least +2 digits, but not more than 3, ranging from 0 to 9.+ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/IDDARt/1) + +### 4.2 Αρνητική Αναζήτηση προς τα Μπροστά + +Η αρνητική αναζήτηση προς τα μπροστά, χρησιμοποιείται όταν θέλουμε όλες τις εκφράσεις που +ταιριάζουν με το μοτίβο που αναζητάμε, που όμως δεν ακολουθούνται από κάποιο άλλο μοτίβο. +Αυτή η αναζήτηση ορίζεται όπως και η παραπάνω αλλά αντί για το σύμβολο `=` χρησιμοποιούμε το `!`, +με αυτό τον τρόπο: `(?!...)`. Ας δούμε την κανονική έκφραση `(T|t)he(?!\sfat)` η οποία: επιστρέφει +όλα τα `The` ή `the` που υπάρχουν στο string εισόδου και δεν ακολουθούνται από την λέξη `fat` +μετά από κενό. + +"[0-9]{2,3}" => The number was 9.9997 but we rounded it off to 10.0. @@ -213,8 +262,9 @@ characters in the range of 0 to 9). [Test the regular expression](https://regex101.com/r/juM86s/1) -We can leave out the second number. For example, the regular expression `[0-9]{2,}` means: Match 2 or more digits. If we also remove -the comma the regular expression `[0-9]{3}` means: Match exactly 3 digits. +We can leave out the second number. For example, the regular expression +`[0-9]{2,}` means: Match 2 or more digits. If we also remove the comma, the +regular expression `[0-9]{3}` means: Match exactly 3 digits.+ +[Essayer l'expression régulière](https://regex101.com/r/8Efx5G/1) + +## 5. Drapeaux + +Les drapeaux sont aussi appelés modifieurs car ils modifient la sortie d'une expression régulière. Ces drapeaux peuvent être utilisés +dans n'importe quel ordre et combinaison et font partie intégrante de la RegExp. + +|Drapeau|Description| +|:----:|----| +|i|Insensible à la casse : Définit que la correspondance sera insensible à la casse.| +|g|Recherche globale : Recherche la correspondance dans la chaine de caractères (string) entière.| +|m|Multiligne : Meta-caractère ancre qui agit sur toutes les lignes.| + +### 5.1 Insensible à la casse + +Le modifieur `i` est utilisé pour faire une correspondance insensible à la casse. Par exemple, l'expression régulière `/The/gi` signifie : la lettre +`T` majuscule, suivie par le caractère `h` minuscule, suivi par le caractère `e` minuscule. Et à la fin de l'expression régulière, le drapeau `i` dit au +moteur d'expression régulière d'ignorer la casse. Comme vous pouvez le voir, nous mettons aussi un drapeau `g` parce que nous voulons chercher le schéma dans +la chaine de caractères (string) entière. + +"[0-9]{2,}" => The number was 9.9997 but we rounded it off to 10.0. @@ -228,13 +278,16 @@ the comma the regular expression `[0-9]{3}` means: Match exactly 3 digits. [Test the regular expression](https://regex101.com/r/Sivu30/1) -## 2.5 Character Group +## 2.5 Capturing Groups -Character group is a group of sub-patterns that is written inside Parentheses `(...)`. As we discussed before that in regular expression -if we put a quantifier after a character then it will repeat the preceding character. But if we put quantifier after a character group then -it repeats the whole character group. For example, the regular expression `(ab)*` matches zero or more repetitions of the character "ab". -We can also use the alternation `|` meta character inside character group. For example, the regular expression `(c|g|p)ar` means: lowercase character `c`, -`g` or `p`, followed by character `a`, followed by character `r`. +A capturing group is a group of subpatterns that is written inside parentheses +`(...)`. As discussed before, in regular expressions, if we put a quantifier +after a character then it will repeat the preceding character. But if we put a quantifier +after a capturing group then it repeats the whole capturing group. For example, +the regular expression `(ab)*` matches zero or more repetitions of the character +"ab". We can also use the alternation `|` meta character inside a capturing group. +For example, the regular expression `(c|g|p)ar` means: a lowercase `c`, +`g` or `p`, followed by `a`, followed by `r`.+ +[Essayer l'expression régulière](https://regex101.com/r/IDDARt/1) + +### 4.2 Recherche en avant négative + +La recherche en avant négative est utilisée quand nous avons besoin de trouver une chaine de caractères (string) qui n'est pas suivie d'un schéma. La recherche en avant négative +est définie de la même manière que la recherche en avant positive mais la seule différence est qu'à la place du signe égal `=` nous utilisons le caractère de négation `!` +i.e. `(?!...)`. Regardons l'expression régulière suivante `[T|t]he(?!\sfat)` qui signifie : trouve tous les mots `The` ou `the` de la chaine de caractères (string) +qui ne sont pas suivis du mot `fat` précédé d'un espace. + +"(c|g|p)ar" => The car is parked in the garage. @@ -242,13 +295,39 @@ We can also use the alternation `|` meta character inside character group. For e [Test the regular expression](https://regex101.com/r/tUxrBG/1) +Note that capturing groups do not only match, but also capture, the characters for use in +the parent language. The parent language could be Python or JavaScript or virtually any +language that implements regular expressions in a function definition. + +### 2.5.1 Non-Capturing Groups + +A non-capturing group is a capturing group that matches the characters but +does not capture the group. A non-capturing group is denoted by a `?` followed by a `:` +within parentheses `(...)`. For example, the regular expression `(?:c|g|p)ar` is similar to +`(c|g|p)ar` in that it matches the same characters but will not create a capture group. + ++ +[Test the regular expression](https://regex101.com/r/8Efx5G/1) + +## 5. Flags + +Flags are also called modifiers because they modify the output of a regular +expression. These flags can be used in any order or combination, and are an +integral part of the RegExp. + +|Flag|Description| +|:----:|----| +|i|Case insensitive: Sets matching to be case-insensitive.| +|g|Global Search: Search for a pattern throughout the input string.| +|m|Multiline: Anchor meta character works on each line.| + +### 5.1 Case Insensitive + +The `i` modifier is used to perform case-insensitive matching. For example, the +regular expression `/The/gi` means: uppercase letter `T`, followed by lowercase +character `h`, followed by character `e`. And at the end of regular expression +the `i` flag tells the regular expression engine to ignore the case. As you can +see we also provided `g` flag because we want to search for the pattern in the +whole input string. + ++"(?:c|g|p)ar" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/Rm7Me8/1) + +Non-capturing groups can come in handy when used in find-and-replace functionality or +when mixed with capturing groups to keep the overview when producing any other kind of output. +See also [4. Lookaround](#4-lookaround). + ## 2.6 Alternation -In regular expression Vertical bar `|` is used to define alternation. Alternation is like a condition between multiple expressions. Now, -you may be thinking that character set and alternation works the same way. But the big difference between character set and alternation -is that character set works on character level but alternation works on expression level. For example, the regular expression -`(T|t)he|car` means: uppercase character `T` or lowercase `t`, followed by lowercase character `h`, followed by lowercase character `e` -or lowercase character `c`, followed by lowercase character `a`, followed by lowercase character `r`. +In a regular expression, the vertical bar `|` is used to define alternation. +Alternation is like an OR statement between multiple expressions. Now, you may be +thinking that character sets and alternation work the same way. But the big +difference between character sets and alternation is that character sets work at the +character level but alternation works at the expression level. For example, the +regular expression `(T|t)he|car` means: either (an uppercase `T` or a lowercase +`t`, followed by a lowercase `h`, followed by a lowercase `e`) OR +(a lowercase `c`, followed by a lowercase `a`, followed by +a lowercase `r`). Note that I included the parentheses for clarity, to show that either expression +in parentheses can be met and it will match."(T|t)he|car" => The car is parked in the garage. @@ -256,13 +335,16 @@ or lowercase character `c`, followed by lowercase character `a`, followed by low [Test the regular expression](https://regex101.com/r/fBXyX0/1) -## 2.7 Escaping special character +## 2.7 Escaping Special Characters -Backslash `\` is used in regular expression to escape the next character. This allows to to specify a symbol as a matching character -including reserved characters `{ } [ ] / \ + * . $ ^ | ?`. To use a special character as a matching character prepend `\` before it. -For example, the regular expression `.` is used to match any character except newline. Now to match `.` in an input string the regular -expression `(f|c|m)at\.?` means: lowercase letter `f`, `c` or `m`, followed by lowercase character `a`, followed by lowercase letter -`t`, followed by optional `.` character. +A backslash `\` is used in regular expressions to escape the next character. This +allows us to include reserved characters such as `{ } [ ] / \ + * . $ ^ | ?` as matching characters. To use one of these special character as a matching character, prepend it with `\`. + +For example, the regular expression `.` is used to match any character except a +newline. Now, to match `.` in an input string, the regular expression +`(f|c|m)at\.?` means: a lowercase `f`, `c` or `m`, followed by a lowercase +`a`, followed by a lowercase `t`, followed by an optional `.` +character.+ +[Test the regular expression](https://regex101.com/r/IDDARt/1) + +### 4.2 Negative Lookahead + +Negative lookahead is used when we need to get all matches from input string +that are not followed by a pattern. Negative lookahead is defined same as we define +positive lookahead but the only difference is instead of equal `=` character we +use negation `!` character i.e. `(?!...)`. Let's take a look at the following +regular expression `(T|t)he(?!\sfat)` which means: get all `The` or `the` words +from input string that are not followed by the word `fat` precedes by a space +character. + +"(f|c|m)at\.?" => The fat cat sat on the mat. @@ -272,18 +354,22 @@ expression `(f|c|m)at\.?` means: lowercase letter `f`, `c` or `m`, followed by l ## 2.8 Anchors -In regular expressions, we use anchors to check if the matching symbol is the starting symbol or ending symbol of the -input string. Anchors are of two types: First type is Caret `^` that check if the matching character is the start -character of the input and the second type is Dollar `$` that checks if matching character is the last character of the -input string. +In regular expressions, we use anchors to check if the matching symbol is the +starting symbol or ending symbol of the input string. Anchors are of two types: +The first type is the caret `^` that checks if the matching character is the first +character of the input and the second type is the dollar sign `$` which checks if a matching +character is the last character of the input string. -### 2.8.1 Caret +### 2.8.1 The Caret -Caret `^` symbol is used to check if matching character is the first character of the input string. If we apply the following regular -expression `^a` (if a is the starting symbol) to input string `abc` it matches `a`. But if we apply regular expression `^b` on above -input string it does not match anything. Because in input string `abc` "b" is not the starting symbol. Let's take a look at another -regular expression `^(T|t)he` which means: uppercase character `T` or lowercase character `t` is the start symbol of the input string, -followed by lowercase character `h`, followed by lowercase character `e`. +The caret symbol `^` is used to check if a matching character is the first character +of the input string. If we apply the following regular expression `^a` (meaning 'a' must be +the starting character) to the string `abc`, it will match `a`. But if we apply +the regular expression `^b` to the above string, it will not match anything. +Because in the string `abc`, the "b" is not the starting character. Let's take a look +at another regular expression `^(T|t)he` which means: an uppercase `T` or +a lowercase `t` must be the first character in the string, followed by a +lowercase `h`, followed by a lowercase `e`.+ +[Prueba la expresión regular](https://regex101.com/r/8Efx5G/1) + +## 5. Indicadores + +Los indicadores también se llaman modificadores porque modifican la salida +de una expresión regular. Estos indicadores se pueden utilizar en cualquier orden +o combinación, y son una parte integral de RegExp. + + +|Indicador|Descripción| +|:----:|----| +|i|Insensible a mayúsculas y minúsculas: Ajusta la coincidencia para que no distinga mayúsculas y minúsculas.| +|g|Búsqueda global: Busca un patrón en toda la cadena de entrada.| +|m|Multilínea: Ancla meta carácter trabaja en cada línea.| + +### 5.1 Mayúsculas y minúsculas + +El modificador `i` se utiliza para realizar la coincidencia entre mayúsculas y +minúsculas. Por ejemplo, la expresión regular `/The/gi` significa: carácter en mayúscula +`T`, seguido del carácter en minúscula `h`, seguido del carácter `e`. Y al final +de la expresión regular, el indicador `i` indica al motor de expresiones +regulares que ignore el caso. Como puede ver, también proveimos el indicador +`g` porque queremos buscar el patrón en toda la cadena de entrada. + + +"(T|t)he" => The car is parked in the garage. @@ -297,11 +383,12 @@ followed by lowercase character `h`, followed by lowercase character `e`. [Test the regular expression](https://regex101.com/r/jXrKne/1) -### 2.8.2 Dollar +### 2.8.2 The Dollar Sign -Dollar `$` symbol is used to check if matching character is the last character of the input string. For example, regular expression -`(at\.)$` means: a lowercase character `a`, followed by lowercase character `t`, followed by a `.` character and the matcher -must be end of the string. +The dollar sign `$` is used to check if a matching character is the last character +in the string. For example, the regular expression `(at\.)$` means: a +lowercase `a`, followed by a lowercase `t`, followed by a `.` +character and the matcher must be at the end of the string.+ +[Teste den regulären Ausdruck](https://regex101.com/r/8Efx5G/1) + +## 5. Modifikatoren + +Modifikatoren (eng. *flags* oder *modifiers*) verändern die Ausgabe eines regulären Ausdrucks. Sie können in beliebiger Kombination oder Reihenfolge +genutzt werden und sind ein integraler Bestandteil regulärer Ausdrücke. + + +|Modifikator|Beschreibung| +|:----:|----| +|i|Schreibungsunabhängig: Unterschiede bei Groß- und Kleinschreibung in den Mustern werden ignoriert.| +|g|Globale Suche: Die Suche geht durch die gesamte Eingabe.| +|m|Mehrzeilig: Anker-Metazeichen funktionieren für Anfang/Ende jeder Zeile.| + +### 5.1 Groß-/Kleinschreibung unempfindlich + +Der `i` Modifikator wird benutzt, um unabhängige Übereinstimmungen bei der Groß-/Kleinschreibung zu finden. Zum Beispiel heißt der reguläre Ausdruck +`/The/gi`: großes `T`, gefolgt von `h`, dann `e`. Und am Ende des Ausdrucks ist der `i` Modifikator zu finden, welcher der Maschine +zu verstehen gibt, dass Groß- und Kleinschreibung ignoriert werden sollen. Wie zu sehen ist, wird auch der `g` Modifikator benutzt, +da wir die gesamte Eingabe nach dem Muster absuchen wollen. + +"(at\.)" => The fat cat. sat. on the mat. @@ -317,26 +404,30 @@ must be end of the string. ## 3. Shorthand Character Sets -Regular expression provides shorthands for the commonly used character sets, which offer convenient shorthands for commonly used -regular expressions. The shorthand character sets are as follows: +There are a number of convenient shorthands for commonly used character sets/ +regular expressions: |Shorthand|Description| |:----:|----| |.|Any character except new line| |\w|Matches alphanumeric characters: `[a-zA-Z0-9_]`| |\W|Matches non-alphanumeric characters: `[^\w]`| -|\d|Matches digit: `[0-9]`| -|\D|Matches non-digit: `[^\d]`| -|\s|Matches whitespace character: `[\t\n\f\r\p{Z}]`| -|\S|Matches non-whitespace character: `[^\s]`| - -## 4. Lookaround - -Lookbehind and lookahead sometimes known as lookaround are specific type of ***non-capturing group*** (Use to match the pattern but not -included in matching list). Lookaheads are used when we have the condition that this pattern is preceded or followed by another certain -pattern. For example, we want to get all numbers that are preceded by `$` character from the following input string `$4.44 and $10.88`. -We will use following regular expression `(?<=\$)[0-9\.]*` which means: get all the numbers which contain `.` character and are preceded -by `$` character. Following are the lookarounds that are used in regular expressions: +|\d|Matches digits: `[0-9]`| +|\D|Matches non-digits: `[^\d]`| +|\s|Matches whitespace characters: `[\t\n\f\r\p{Z}]`| +|\S|Matches non-whitespace characters: `[^\s]`| + +## 4. Lookarounds + +Lookbehinds and lookaheads (also called lookarounds) are specific types of +***non-capturing groups*** (used to match a pattern but without including it in the matching +list). Lookarounds are used when a pattern must be +preceded or followed by another pattern. For example, imagine we want to get all +numbers that are preceded by the `$` character from the string +`$4.44 and $10.88`. We will use the following regular expression `(?<=\$)[0-9\.]*` +which means: get all the numbers which contain the `.` character and are preceded +by the `$` character. These are the lookarounds that are used in regular +expressions: |Symbol|Description| |:----:|----| @@ -347,73 +438,84 @@ by `$` character. Following are the lookarounds that are used in regular express ### 4.1 Positive Lookahead -The positive lookahead asserts that the first part of the expression must be followed by the lookahead expression. The returned match -only contains the text that is matched by the first part of the expression. To define a positive lookahead, parentheses are used. Within -those parentheses, a question mark with equal sign is used like this: `(?=...)`. Lookahead expression is written after the equal sign inside -parentheses. For example, the regular expression `[T|t]he(?=\sfat)` means: optionally match lowercase letter `t` or uppercase letter `T`, -followed by letter `h`, followed by letter `e`. In parentheses we define positive lookahead which tells regular expression engine to match -`The` or `the` which are followed by the word `fat`. +The positive lookahead asserts that the first part of the expression must be +followed by the lookahead expression. The returned match only contains the text +that is matched by the first part of the expression. To define a positive +lookahead, parentheses are used. Within those parentheses, a question mark with +an equals sign is used like this: `(?=...)`. The lookahead expressions is written after +the equals sign inside parentheses. For example, the regular expression +`(T|t)he(?=\sfat)` means: match either a lowercase `t` or an uppercase + `T`, followed by the letter `h`, followed by the letter `e`. In parentheses we +define a positive lookahead which tells the regular expression engine to match `The` +or `the` only if it's followed by the word `fat`.[Test the regular expression](https://regex101.com/r/8Efx5G/1) ## 5. Flags -Flags are also called modifiers because they modify the output of a regular expression. These flags can be used in any order or -combination, and are an integral part of the RegExp. +Flags are also called modifiers because they modify the output of a regular +expression. These flags can be used in any order or combination, and are an +integral part of the RegExp. |Flag|Description| |:----:|----| -|i|Case insensitive: Sets matching to be case-insensitive.| -|g|Global Search: Search for a pattern throughout the input string.| -|m|Multiline: Anchor meta character works on each line.| +|i|Case insensitive: Match will be case-insensitive.| +|g|Global Search: Match all instances, not just the first.| +|m|Multiline: Anchor meta characters work on each line.| ### 5.1 Case Insensitive -The `i` modifier is used to perform case-insensitive matching. For example, the regular expression `/The/gi` means: uppercase letter -`T`, followed by lowercase character `h`, followed by character `e`. And at the end of regular expression the `i` flag tells the -regular expression engine to ignore the case. As you can see we also provided `g` flag because we want to search for the pattern in -the whole input string. +The `i` modifier is used to perform case-insensitive matching. For example, the +regular expression `/The/gi` means: an uppercase `T`, followed by a lowercase +`h`, followed by an `e`. And at the end of regular expression +the `i` flag tells the regular expression engine to ignore the case. As you can +see, we also provided `g` flag because we want to search for the pattern in the +whole input string.-"[T|t]he(?=\sfat)" => The fat cat sat on the mat. +"(T|t)he(?=\sfat)" => The fat cat sat on the mat.[Test the regular expression](https://regex101.com/r/IDDARt/1) ### 4.2 Negative Lookahead -Negative lookahead is used when we need to get all matches from input string that are not followed by a pattern. Negative lookahead -defined same as we define positive lookahead but the only difference is instead of equal `=` character we use negation `!` character -i.e. `(?!...)`. Let's take a look at the following regular expression `[T|t]he(?!\sfat)` which means: get all `The` or `the` words from -input string that are not followed by the word `fat` precedes by a space character. +Negative lookaheads are used when we need to get all matches from an input string +that are not followed by a certain pattern. A negative lookahead is written the same way as a +positive lookahead. The only difference is, instead of an equals sign `=`, we +use an exclamation mark `!` to indicate negation i.e. `(?!...)`. Let's take a look at the following +regular expression `(T|t)he(?!\sfat)` which means: get all `The` or `the` words +from the input string that are not followed by a space character and the word `fat`.-"[T|t]he(?!\sfat)" => The fat cat sat on the mat. +"(T|t)he(?!\sfat)" => The fat cat sat on the mat.[Test the regular expression](https://regex101.com/r/V32Npg/1) ### 4.3 Positive Lookbehind -Positive lookbehind is used to get all the matches that are preceded by a specific pattern. Positive lookbehind is denoted by -`(?<=...)`. For example, the regular expression `(?<=[T|t]he\s)(fat|mat)` means: get all `fat` or `mat` words from input string that -are after the word `The` or `the`. +Positive lookbehinds are used to get all the matches that are preceded by a +specific pattern. Positive lookbehinds are written `(?<=...)`. For example, the +regular expression `(?<=(T|t)he\s)(fat|mat)` means: get all `fat` or `mat` words +from the input string that come after the word `The` or `the`.-"(?<=[T|t]he\s)(fat|mat)" => The fat cat sat on the mat. +"(?<=(T|t)he\s)(fat|mat)" => The fat cat sat on the mat.[Test the regular expression](https://regex101.com/r/avH165/1) ### 4.4 Negative Lookbehind -Negative lookbehind is used to get all the matches that are not preceded by a specific pattern. Negative lookbehind is denoted by -`(? -"(?<![T|t]he\s)(cat)" => The cat sat on cat. +"(?<!(T|t)he\s)(cat)" => The cat sat on cat."The" => The fat cat sat on the mat. @@ -427,12 +529,13 @@ the whole input string. [Test the regular expression](https://regex101.com/r/ahfiuh/1) -### 5.2 Global search +### 5.2 Global Search -The `g` modifier is used to perform a global match (find all matches rather than stopping after the first match). For example, the -regular expression`/.(at)/g` means: any character except new line, followed by lowercase character `a`, followed by lowercase -character `t`. Because we provided `g` flag at the end of the regular expression now it will find every matches from whole input -string. +The `g` modifier is used to perform a global match (finds all matches rather than +stopping after the first match). For example, the regular expression`/.(at)/g` +means: any character except a new line, followed by a lowercase `a`, +followed by a lowercase `t`. Because we provided the `g` flag at the end of +the regular expression, it will now find all matches in the input string, not just the first one (which is the default behavior).+ +[Teste den regulären Ausdruck](https://regex101.com/r/IDDARt/1) + +### 4.2 Negatives Vorausschauen (Lookahead) + +Negative Lookaheads werden verwendet, um alle Übereinstimmungen in einer Zeichenkette zu bekommen, auf die **nicht** ein bestimmtes Muster folgt. +Ein Negativer Lookahead wird wie ein positiver Lookahead definiert, nur dass statt einem Gleichheitszeichen ein Ausrufezeichen `!` benutzt wird, d.h. +`(?!...)`. Aus dem regulären Ausdruck `(T|t)he(?!\sfat)` folgt somit: alle `The` oder `the`, auf die **kein** Leerzeichen und das Wort `fat` folgt, stimmen überein. + +"/.(at)/" => The fat cat sat on the mat. @@ -448,10 +551,13 @@ string. ### 5.3 Multiline -The `m` modifier is used to perform a multi-line match. As we discussed earlier anchors `(^, $)` are used to check if pattern is -the beginning of the input or end of the input string. But if we want that anchors works on each line we use `m` flag. For example, the -regular expression `/at(.)?$/gm` means: lowercase character `a`, followed by lowercase character `t`, optionally anything except new -line. And because of `m` flag now regular expression engine matches pattern at the end of each line in a string. +The `m` modifier is used to perform a multi-line match. As we discussed earlier, +anchors `(^, $)` are used to check if a pattern is at the beginning of the input or +the end. But if we want the anchors to work on each line, we use +the `m` flag. For example, the regular expression `/at(.)?$/gm` means: a lowercase +`a`, followed by a lowercase `t` and, optionally, anything except +a new line. And because of the `m` flag, the regular expression engine now matches patterns +at the end of each line in a string.+ +[在线练习](https://regex101.com/r/8Efx5G/1) + +## 5. 标志 + +标志也叫模式修正符,因为它可以用来修改表达式的搜索结果。 +这些标志可以任意的组合使用,它也是整个正则表达式的一部分。 + +|标志|描述| +|:----:|----| +|i|忽略大小写。| +|g|全局搜索。| +|m|多行修饰符:锚点元字符 `^` `$` 工作范围在每行的起始。| + +### 5.1 忽略大小写 (Case Insensitive) + +修饰语 `i` 用于忽略大小写。 +例如,表达式 `/The/gi` 表示在全局搜索 `The`,在后面的 `i` 将其条件修改为忽略大小写,则变成搜索 `the` 和 `The`,`g` 表示全局搜索。 + +"/.at(.)?$/" => The fat @@ -469,36 +575,29 @@ line. And because of `m` flag now regular expression engine matches pattern at t [Test the regular expression](https://regex101.com/r/E88WE2/1) -## Bonus - -* *Positive Integers*: `^\d+$` -* *Negative Integers*: `^-\d+$` -* *US Phone Number*: `^+?[\d\s]{3,}$` -* *US Phone with code*: `^+?[\d\s]+(?[\d\s]{10,}$` -* *Integers*: `^-?\d+$` -* *Username*: `^[\w.]{4,16}$` -* *Alpha-numeric characters*: `^[a-zA-Z0-9]*$` -* *Alpha-numeric characters with spaces*: `^[a-zA-Z0-9 ]*$` -* *Password*: `^(?=^.{6,}$)((?=.*[A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z]))^.*$` -* *email*: `^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})*$` -* *IPv4 address*: `^((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))*$` -* *Lowercase letters only*: `^([a-z])*$` -* *Uppercase letters only*: `^([A-Z])*$` -* *URL*: `^(((http|https|ftp):\/\/)?([[a-zA-Z0-9]\-\.])+(\.)([[a-zA-Z0-9]]){2,4}([[a-zA-Z0-9]\/+=%&_\.~?\-]*))*$` -* *VISA credit card numbers*: `^(4[0-9]{12}(?:[0-9]{3})?)*$` -* *Date (DD/MM/YYYY)*: `^(0?[1-9]|[12][0-9]|3[01])[- /.](0?[1-9]|1[012])[- /.](19|20)?[0-9]{2}$` -* *Date (MM/DD/YYYY)*: `^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2}$` -* *Date (YYYY/MM/DD)*: `^(19|20)?[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])$` -* *MasterCard credit card numbers*: `^(5[1-5][0-9]{14})*$` -* *Hashtags*: Including hashtags with preceding text (abc123#xyz456) or containing white spaces within square brackets (#[foo bar]) : `\S*#(?:\[[^\]]+\]|\S+)` -* *@mentions*: `\B@[a-z0-9_-]+` +## 6. Greedy vs Lazy Matching +By default, a regex will perform a greedy match, which means the match will be as long as +possible. We can use `?` to match in a lazy way, which means the match should be as short as possible. + ++ +[在线练习](https://regex101.com/r/IDDARt/1) + +### 4.2 `?!...` 负先行断言 + +负先行断言 `?!` 用于筛选所有匹配结果,筛选条件为其后 不跟随着断言中定义的格式。 +`正先行断言` 定义和 `负先行断言` 一样,区别就是 `=` 替换成 `!` 也就是 `(?!...)`。 + +表达式 `(T|t)he(?!\sfat)` 匹配 `The` 和 `the`,且其后不跟着 `(空格)fat`。 + ++"/(.*at)/" => The fat cat sat on the mat.+ + +[Test the regular expression](https://regex101.com/r/AyAdgJ/1) + ++"/(.*?at)/" => The fat cat sat on the mat.+ + +[Test the regular expression](https://regex101.com/r/AyAdgJ/2) + + ## Contribution -* Report issues -* Open pull request with improvements -* Spread the word -* Reach out to me directly at ziishaned@gmail.com or [](https://twitter.com/ziishaned) +* Open a pull request with improvements +* Discuss ideas in issues +* Spread the word ## License -MIT © [Zeeshan Ahmed](mailto:ziishaned@gmail.com) +MIT © Zeeshan Ahmad diff --git a/img/img_original.png b/img/img_original.png new file mode 100644 index 00000000..da1c5fa2 Binary files /dev/null and b/img/img_original.png differ diff --git a/img/regexp-cn.png b/img/regexp-cn.png new file mode 100644 index 00000000..0d1c9340 Binary files /dev/null and b/img/regexp-cn.png differ diff --git a/img/regexp-de.png b/img/regexp-de.png new file mode 100644 index 00000000..824e586a Binary files /dev/null and b/img/regexp-de.png differ diff --git a/img/regexp-en.png b/img/regexp-en.png new file mode 100644 index 00000000..46b1a0b9 Binary files /dev/null and b/img/regexp-en.png differ diff --git a/img/regexp-es.png b/img/regexp-es.png new file mode 100644 index 00000000..b8a76240 Binary files /dev/null and b/img/regexp-es.png differ diff --git a/img/regexp-fr.png b/img/regexp-fr.png new file mode 100644 index 00000000..7712d2e6 Binary files /dev/null and b/img/regexp-fr.png differ diff --git a/img/regexp-he.png b/img/regexp-he.png new file mode 100644 index 00000000..c09457ed Binary files /dev/null and b/img/regexp-he.png differ diff --git a/img/regexp-hu.png b/img/regexp-hu.png new file mode 100644 index 00000000..70d1f516 Binary files /dev/null and b/img/regexp-hu.png differ diff --git a/img/regexp-id.png b/img/regexp-id.png new file mode 100644 index 00000000..9a93f87c Binary files /dev/null and b/img/regexp-id.png differ diff --git a/img/regexp-pl.png b/img/regexp-pl.png new file mode 100644 index 00000000..5da2cd42 Binary files /dev/null and b/img/regexp-pl.png differ diff --git a/img/regexp-ru.png b/img/regexp-ru.png new file mode 100644 index 00000000..a28870cc Binary files /dev/null and b/img/regexp-ru.png differ diff --git a/img/regexp-tr.png b/img/regexp-tr.png new file mode 100644 index 00000000..9285dfcf Binary files /dev/null and b/img/regexp-tr.png differ diff --git a/img/regexp.svg b/img/regexp.svg new file mode 100644 index 00000000..46d9f188 --- /dev/null +++ b/img/regexp.svg @@ -0,0 +1,397 @@ + + + + diff --git a/translations/README-cn.md b/translations/README-cn.md new file mode 100644 index 00000000..c8925d1d --- /dev/null +++ b/translations/README-cn.md @@ -0,0 +1,540 @@ ++
+ + + +## 翻译: + +* [English](../README.md) +* [German](../translations/README-de.md) +* [Español](../translations/README-es.md) +* [Français](../translations/README-fr.md) +* [Português do Brasil](../translations/README-pt_BR.md) +* [中文版](../translations/README-cn.md) +* [日本語](../translations/README-ja.md) +* [한국어](../translations/README-ko.md) +* [Turkish](../translations/README-tr.md) +* [Greek](../translations/README-gr.md) +* [Magyar](../translations/README-hu.md) +* [Polish](../translations/README-pl.md) +* [Русский](../translations/README-ru.md) +* [Tiếng Việt](../translations/README-vn.md) +* [فارسی](../translations/README-fa.md) +* [עברית](../translations/README-he.md) + +## 什么是正则表达式? + +[](https://gum.co/learn-regex) + +> 正则表达式是一组由字母和符号组成的特殊文本,它可以用来从文本中找出满足你想要的格式的句子。 + +一个正则表达式是一种从左到右匹配主体字符串的模式。 +正则表达式可以从一个基础字符串中根据一定的匹配模式替换文本中的字符串、验证表单、提取字符串等等。 +“Regular expression”这个词比较拗口,我们常使用缩写的术语“regex”或“regexp”。 + +想象你正在写一个应用,然后你想设定一个用户命名的规则,让用户名包含字符、数字、下划线和连字符,以及限制字符的个数,好让名字看起来没那么丑。 +我们使用以下正则表达式来验证一个用户名: + +
+ ++ +
+
+ ++
+ +以上的正则表达式可以接受 `john_doe`、`jo-hn_doe`、`john12_as`。 +但不匹配`Jo`,因为它包含了大写的字母而且太短了。 + +目录 +================= + + * [1. 基本匹配](#1-基本匹配) + * [2. 元字符](#2-元字符) + * [2.1 点运算符 .](#21-点运算符-) + * [2.2 字符集](#22-字符集) + * [2.2.1 否定字符集](#221-否定字符集) + * [2.3 重复次数](#23-重复次数) + * [2.3.1 * 号](#231--号) + * [2.3.2 + 号](#232--号) + * [2.3.3 ? 号](#233--号) + * [2.4 {} 号](#24--号) + * [2.5 (...) 特征标群](#25--特征标群) + * [2.6 | 或运算符](#26--或运算符) + * [2.7 转码特殊字符](#27-转码特殊字符) + * [2.8 锚点](#28-锚点) + * [2.8.1 ^ 号](#281--号) + * [2.8.2 $ 号](#282--号) +* [3. 简写字符集](#3-简写字符集) +* [4. 零宽度断言(前后预查)](#4-零宽度断言前后预查) + * [4.1 ?=... 正先行断言](#41--正先行断言) + * [4.2 ?!... 负先行断言](#42--负先行断言) + * [4.3 ?<= ... 正后发断言](#43---正后发断言) + * [4.4 ?<!... 负后发断言](#44--负后发断言) +* [5. 标志](#5-标志) + * [5.1 忽略大小写(Case Insensitive)](#51-忽略大小写-case-insensitive) + * [5.2 全局搜索(Global search)](#52-全局搜索-global-search) + * [5.3 多行修饰符(Multiline)](#53-多行修饰符-multiline) +* [额外补充](#额外补充) +* [贡献](#贡献) +* [许可证](#许可证) + +## 1. 基本匹配 + +正则表达式其实就是在执行搜索时的格式,它由一些字母和数字组合而成。 +例如:一个正则表达式 `the`,它表示一个规则:由字母 `t` 开始,接着是 `h`,再接着是 `e`。 + ++
+"the" => The fat cat sat on the mat. ++ +[在线练习](https://regex101.com/r/dmRygT/1) + +正则表达式 `123` 匹配字符串 `123`。它逐个字符的与输入的正则表达式做比较。 + +正则表达式是大小写敏感的,所以 `The` 不会匹配 `the`。 + ++"The" => The fat cat sat on the mat. ++ +[在线练习](https://regex101.com/r/1paXsy/1) + +## 2. 元字符 + +正则表达式主要依赖于元字符。 +元字符不代表他们本身的字面意思,他们都有特殊的含义。一些元字符写在方括号中的时候有一些特殊的意思。以下是一些元字符的介绍: + +|元字符|描述| +|:----:|----| +|.|句号匹配任意单个字符除了换行符。| +|[ ]|字符种类。匹配方括号内的任意字符。| +|[^ ]|否定的字符种类。匹配除了方括号里的任意字符| +|*|匹配 >=0 个重复的在 * 号之前的字符。| +|+|匹配 >=1 个重复的 + 号前的字符。| +|?|标记 ? 之前的字符为可选。| +|{n,m}|匹配 num 个大括号之前的字符或字符集 (n <= num <= m)。| +|(xyz)|字符集,匹配与 xyz 完全相等的字符串。| +|||或运算符,匹配符号前或后的字符。| +|\|转义字符,用于匹配一些保留的字符[ ] ( ) { } . * + ? ^ $ \ |
| +|^|从开始行开始匹配。| +|$|从末端开始匹配。| + +## 2.1 点运算符 `.` + +`.` 是元字符中最简单的例子。 +`.` 匹配任意单个字符,但不匹配换行符。 +例如,表达式 `.ar` 匹配一个任意字符后面跟着是 `a` 和 `r` 的字符串。 + ++".ar" => The car parked in the garage. ++ +[在线练习](https://regex101.com/r/xc9GkU/1) + +## 2.2 字符集 + +字符集也叫做字符类。 +方括号用来指定一个字符集。 +在方括号中使用连字符来指定字符集的范围。 +在方括号中的字符集不关心顺序。 +例如,表达式 `[Tt]he` 匹配 `the` 和 `The`。 + ++"[Tt]he" => The car parked in the garage. ++ +[在线练习](https://regex101.com/r/2ITLQ4/1) + +方括号的句号就表示句号。 +表达式 `ar[.]` 匹配 `ar.` 字符串。 + ++"ar[.]" => A garage is a good place to park a car. ++ +[在线练习](https://regex101.com/r/wL3xtE/1) + +### 2.2.1 否定字符集 + +一般来说 `^` 表示一个字符串的开头,但它用在一个方括号的开头的时候,它表示这个字符集是否定的。 +例如,表达式 `[^c]ar` 匹配一个后面跟着 `ar` 的除了 `c` 的任意字符。 + ++"[^c]ar" => The car parked in the garage. ++ +[在线练习](https://regex101.com/r/nNNlq3/1) + +## 2.3 重复次数 + +后面跟着元字符 `+`,`*` or `?` 的,用来指定匹配子模式的次数。 +这些元字符在不同的情况下有着不同的意思。 + +### 2.3.1 `*` 号 + +`*` 号匹配在 `*` 之前的字符出现 `大于等于0` 次。 +例如,表达式 `a*` 匹配 0 或更多个以 a 开头的字符。表达式 `[a-z]*` 匹配一个行中所有以小写字母开头的字符串。 + ++"[a-z]*" => The car parked in the garage #21. ++ +[在线练习](https://regex101.com/r/7m8me5/1) + +`*` 字符和 `.` 字符搭配可以匹配所有的字符 `.*`。 +`*` 和表示匹配空格的符号 `\s` 连起来用,如表达式 `\s*cat\s*` 匹配 0 或更多个空格开头和 0 或更多个空格结尾的 cat 字符串。 + ++"\s*cat\s*" => The fat cat sat on the concatenation. ++ +[在线练习](https://regex101.com/r/gGrwuz/1) + +### 2.3.2 `+` 号 + +`+` 号匹配 `+` 号之前的字符出现 >=1 次。 +例如表达式 `c.+t` 匹配以首字母 `c` 开头以 `t` 结尾,中间跟着至少一个字符的字符串。 + ++"c.+t" => The fat cat sat on the mat. ++ +[在线练习](https://regex101.com/r/Dzf9Aa/1) + +### 2.3.3 `?` 号 + +在正则表达式中元字符 `?` 标记在符号前面的字符为可选,即出现 0 或 1 次。 +例如,表达式 `[T]?he` 匹配字符串 `he` 和 `The`。 + ++"[T]he" => The car is parked in the garage. ++ +[在线练习](https://regex101.com/r/cIg9zm/1) + ++"[T]?he" => The car is parked in the garage. ++ +[在线练习](https://regex101.com/r/kPpO2x/1) + +## 2.4 `{}` 号 + +在正则表达式中 `{}` 是一个量词,常用来限定一个或一组字符可以重复出现的次数。 +例如,表达式 `[0-9]{2,3}` 匹配最少 2 位最多 3 位 0~9 的数字。 + ++"[0-9]{2,3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[在线练习](https://regex101.com/r/juM86s/1) + +我们可以省略第二个参数。 +例如,`[0-9]{2,}` 匹配至少两位 0~9 的数字。 +如果逗号也省略掉则表示重复固定的次数。 +例如,`[0-9]{3}` 匹配 3 位数字。 + ++"[0-9]{2,}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[在线练习](https://regex101.com/r/Gdy4w5/1) + ++"[0-9]{3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[在线练习](https://regex101.com/r/Sivu30/1) + +## 2.5 `(...)` 捕获组 + +特征标群是一组写在 `(...)` 中的子模式。`(...)` 中包含的内容将会被看成一个整体,和数学中小括号( )的作用相同。 +例如,表达式 `(ab)*` 匹配连续出现 0 或更多个 `ab`。 +如果没有使用 `(...)` ,那么表达式 `ab*` 将匹配连续出现 0 或更多个 `b`。 +再比如之前说的 `{}` 是用来表示前面一个字符出现指定次数。 +但如果在 `{}` 前加上特征标群 `(...)` 则表示整个标群内的字符重复 N 次。 +我们还可以在 `()` 中用或字符 `|` 表示或。例如,`(c|g|p)ar` 匹配 `car` 或 `gar` 或 `par`. + ++"(c|g|p)ar" => The car is parked in the garage. ++ +[在线练习](https://regex101.com/r/tUxrBG/1) + +请注意,特征标群不仅会匹配,而且会捕获,可以在宿主语言中被引用。 +宿主语言可以是 Python 或 JavaScript 或几乎任何在函数定义中实现正则表达式的语言。 + +### 2.5.1 非捕获组 + +非捕获组匹配字符但不捕获该组。 一个非捕获组由在括号 `(...)` 内的一个 `?` 后跟一个 `:` 表示。 例如,正则表达式 `(?:c|g|p)ar` 和 `(c|g|p)ar` 类似,可以匹配相同的字符,但不会创建捕获组。 + ++"(?:c|g|p)ar" => The car is parked in the garage. ++ +[在线练习](https://regex101.com/r/Rm7Me8/1) + +非捕获组用于查找和替换功能,或与捕获组混合以在生成任何其他类型的输出的时候,不记录匹配的内容。 +可参考 [4. 零宽度断言(前后预查)](#4-零宽度断言前后预查)。 + +## 2.6 `|` 或运算符 + +或运算符就表示或,用作判断条件。 + +例如 `(T|t)he|car` 匹配 `(T|t)he` 或 `car`。 + ++"(T|t)he|car" => The car is parked in the garage. ++ +[在线练习](https://regex101.com/r/fBXyX0/1) + +## 2.7 转义特殊字符 + +反斜线 `\` 在表达式中用于转义紧跟其后的字符。 +用于指定 `{ } [ ] / \ + * . $ ^ | ?` 这些特殊字符。 +如果想要匹配这些特殊字符则要在其前面加上反斜线 `\`。 + +例如 `.` 是用来匹配除换行符外的所有字符的。如果想要匹配句子中的 `.` 则要写成 `\.`。 +以下这个例子 `\.?` 是选择性匹配 `.`。 + ++"(f|c|m)at\.?" => The fat cat sat on the mat. ++ +[在线练习](https://regex101.com/r/DOc5Nu/1) + +## 2.8 锚点 + +在正则表达式中,想要匹配指定开头或结尾的字符串就要使用到锚点。`^` 指定开头,`$` 指定结尾。 + +### 2.8.1 `^` 号 + +`^` 用来检查匹配的字符串是否在所匹配字符串的开头。 + +例如,在 `abc` 中使用表达式 `^a` 会得到结果 `a`。 +但如果使用 `^b` 将匹配不到任何结果。 +因为字符串 `abc` 并不是以 b 开头。 + +例如,`^(T|t)he` 匹配以 `The` 或 `the` 开头的字符串。 + ++"(T|t)he" => The car is parked in the garage. ++ +[在线练习](https://regex101.com/r/5ljjgB/1) + ++"^(T|t)he" => The car is parked in the garage. ++ +[在线练习](https://regex101.com/r/jXrKne/1) + +### 2.8.2 `$` 号 + +同理于 `^` 号,`$` 号用来匹配字符是否是最后一个。 + +例如,`(at\.)$` 匹配以 `at.` 结尾的字符串。 + ++"(at\.)" => The fat cat. sat. on the mat. ++ +[在线练习](https://regex101.com/r/y4Au4D/1) + ++"(at\.)$" => The fat cat. sat. on the mat. ++ +[在线练习](https://regex101.com/r/t0AkOd/1) + +## 3. 简写字符集 + +正则表达式提供一些常用的字符集简写。如下: + +|简写|描述| +|:----:|----| +|.|除换行符外的所有字符| +|\w|匹配所有字母数字,等同于 `[a-zA-Z0-9_]`| +|\W|匹配所有非字母数字,即符号,等同于: `[^\w]`| +|\d|匹配数字: `[0-9]`| +|\D|匹配非数字: `[^\d]`| +|\s|匹配所有空格字符,等同于: `[\t\n\f\r\p{Z}]`| +|\S|匹配所有非空格字符: `[^\s]`| +|\f|匹配一个换页符| +|\n|匹配一个换行符| +|\r|匹配一个回车符| +|\t|匹配一个制表符| +|\v|匹配一个垂直制表符| +|\p|匹配 CR/LF(等同于 `\r\n`),用来匹配 DOS 行终止符| + +## 4. 零宽度断言(前后预查) + +先行断言和后发断言(合称 lookaround)都属于**非捕获组**(用于匹配模式,但不包括在匹配列表中)。当我们需要一个模式的前面或后面有另一个特定的模式时,就可以使用它们。 + +例如,我们希望从下面的输入字符串 `$4.44` 和 `$10.88` 中获得所有以 `$` 字符开头的数字,我们将使用以下的正则表达式 `(?<=\$)[0-9\.]*`。意思是:获取所有包含 `.` 并且前面是 `$` 的数字。 + +零宽度断言如下: + +|符号|描述| +|:----:|----| +|?=|正先行断言-存在| +|?!|负先行断言-排除| +|?<=|正后发断言-存在| +|? +"(T|t)he(?=\sfat)" => The fat cat sat on the mat. ++"(T|t)he(?!\sfat)" => The fat cat sat on the mat. ++ +[在线练习](https://regex101.com/r/V32Npg/1) + +### 4.3 `?<= ...` 正后发断言 + +正后发断言记作 `(?<=...)`,用于筛选所有匹配结果,筛选条件为 其前跟随着断言中定义的格式。 +例如,表达式 `(?<=(T|t)he\s)(fat|mat)` 匹配 `fat` 和 `mat`,且其前跟着 `The` 或 `the`。 + ++"(?<=(T|t)he\s)(fat|mat)" => The fat cat sat on the mat. ++ +[在线练习](https://regex101.com/r/avH165/1) + +### 4.4 `? +"(?<!(T|t)he\s)(cat)" => The cat sat on cat. ++"The" => The fat cat sat on the mat. ++ +[在线练习](https://regex101.com/r/dpQyf9/1) + ++"/The/gi" => The fat cat sat on the mat. ++ +[在线练习](https://regex101.com/r/ahfiuh/1) + +### 5.2 全局搜索 (Global search) + +修饰符 `g` 常用于执行一个全局搜索匹配,即(不仅仅返回第一个匹配的,而是返回全部)。 +例如,表达式 `/.(at)/g` 表示搜索 任意字符(除了换行)+ `at`,并返回全部结果。 + ++"/.(at)/" => The fat cat sat on the mat. ++ +[在线练习](https://regex101.com/r/jnk6gM/1) + ++"/.(at)/g" => The fat cat sat on the mat. ++ +[在线练习](https://regex101.com/r/dO1nef/1) + +### 5.3 多行修饰符 (Multiline) + +多行修饰符 `m` 常用于执行一个多行匹配。 + +像之前介绍的 `(^,$)` 用于检查格式是否是在待检测字符串的开头或结尾。但我们如果想要它在每行的开头和结尾生效,我们需要用到多行修饰符 `m`。 + +例如,表达式 `/at(.)?$/gm` 表示小写字符 `a` 后跟小写字符 `t` ,末尾可选除换行符外任意字符。根据 `m` 修饰符,现在表达式匹配每行的结尾。 + ++"/.at(.)?$/" => The fat + cat sat + on the mat. ++ +[在线练习](https://regex101.com/r/hoGMkP/1) + ++"/.at(.)?$/gm" => The fat + cat sat + on the mat. ++ +[在线练习](https://regex101.com/r/E88WE2/1) + +### 6. 贪婪匹配与惰性匹配 (Greedy vs lazy matching) + +正则表达式默认采用贪婪匹配模式,在该模式下意味着会匹配尽可能长的子串。我们可以使用 `?` 将贪婪匹配模式转化为惰性匹配模式。 + ++"/(.*at)/" => The fat cat sat on the mat.+ +[在线练习](https://regex101.com/r/AyAdgJ/1) + ++"/(.*?at)/" => The fat cat sat on the mat.+ +[在线练习](https://regex101.com/r/AyAdgJ/2) + +## 贡献 + +* 报告问题 +* 开放合并请求 +* 传播此文档 +* 直接和我联系 ziishaned@gmail.com 或 [](https://twitter.com/ziishaned) + +## 许可证 + +MIT © [Zeeshan Ahmad](https://twitter.com/ziishaned) diff --git a/translations/README-de.md b/translations/README-de.md new file mode 100644 index 00000000..cc1150a0 --- /dev/null +++ b/translations/README-de.md @@ -0,0 +1,534 @@ ++
+ +## Translations: + +* [English](../README.md) +* [German](../translations/README-de.md) +* [Español](../translations/README-es.md) +* [Français](../translations/README-fr.md) +* [Português do Brasil](../translations/README-pt_BR.md) +* [中文版](../translations/README-cn.md) +* [日本語](../translations/README-ja.md) +* [한국어](../translations/README-ko.md) +* [Turkish](../translations/README-tr.md) +* [Greek](../translations/README-gr.md) +* [Magyar](../translations/README-hu.md) +* [Polish](../translations/README-pl.md) +* [Русский](../translations/README-ru.md) +* [Tiếng Việt](../translations/README-vn.md) +* [فارسی](../translations/README-fa.md) +* [עברית](../translations/README-he.md) + +## Was sind Reguläre Ausdrücke? + +[](https://gum.co/learn-regex) + +> Ein regulärer Ausdruck ist eine Gruppe von Buchstaben und Symbolen, die benutzt werden um ein bestimmtes Muster in einem Text zu finden. +Ein regulärer Ausdruck ist ein Muster, das mit einem zu durchsuchenden Text von links nach rechts abgeglichen wird. Die Bezeichnung +"Regulärer Ausdruck" ist in der Praxis unüblich und stattdessen wird häufig die Englische Abkürzung "Regex" oder "RegExp" (*regular expression*) verwendet. Reguläre +Ausdrücke werden verwendet, um Fragemente eines Textes zu ersetzen, Formulare zu validieren, Segmente eines Textes anhand eines +Musters zu extrahieren und für vieles mehr. + +Angenommen, Du schreibst eine Anwendung und möchtest die Regeln definieren, nach denen ein Benutzer seinen Benutzernamen auswählen +kann. Wir möchten festlegen, dass der Benutzernamen Buchstaben, Ziffern, Unter- und Bindestriche beinhalten darf. Außerdem wollen +wir die Anzahl der Zeichen limitieren, damit der Name nicht unlesbar wird. Dazu verwenden wir den folgenden regulären Ausdruck: +
+ ++ +
++
+ +Der abgebildete reguläre Ausdruck erlaubt bspw. Die Eingaben `john_doe`, `jo-hn_doe` und `john12_as`. Die Eingabe `Jo` wird nicht akzeptiert, weil sie einen Großbuchstaben enthält und zu kurz ist. + +## Inhaltsverzeichnis + +- [Einfache Muster](#1-einfache-muster) +- [Metazeichen](#2-metazeichen) + - [Punkt](#21-punkt) + - [Zeichenklasse](#22-zeichenklasse) + - [Negierte Zeichenklasse](#221-negierte-zeichenklasse) + - [Wiederholungen](#23-wiederholungen) + - [Stern *](#231-stern) + - [Plus +](#232-plus) + - [Fragezeichen ?](#233-fragezeichen) + - [Geschweifte Klammern {}](#24-geschweifte-klammern) + - [Gruppierung ()](#25-gruppierung) + - [Alternation |](#26-alternation) + - [Escaping \](#27-escaping) + - [Anker](#28-anker) + - [Zirkumflex ^](#281-zirkumflex) + - [Dollar $](#282-dollar) +- [Vordefinierte Zeichenklassen](#3-vordefinierte-zeichenklassen) +- [Lookaround](#4-lookaround) + - [Positiver Lookahead](#41-positiver-lookahead) + - [Negativer Lookahead](#42-negativer-lookahead) + - [Positiver Lookbehind](#43-positiver-lookbehind) + - [Negativer Lookbehind](#44-negativer-lookbehind) +- [Modifikatoren](#5-modifikatoren) + - [Schreibungsunabhängig i](#51-schreibungsunbhängig) + - [Globale Suche](#52-globale-suche) + - [Mehrzeilig](#53-mehrzeilig) +- [Gierige vs Faule Übereinstimmung](#6-gierige-vs-faule-übereinstimmung) + +## 1. Einfache Muster + +Ein regulärer Ausdruck ist einfach nur ein Muster von Zeichen, welches für eine Suche in Text genutzt wird. Der reguläre Ausdruck `the` heißt zum Beispiel: der Buchstabe `t`, gefolgt von dem Buchstaben `h`, gefolgt von dem Buchstaben `e`. + ++
+"the" => The fat cat sat on the mat. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/dmRygT/1) + +Der reguläre Ausdruck `123` entspricht der Zeichenkette `123`. Auf Übereinstimmung mit einer Zeichenkette wird er überprüft, indem jedes Zeichen in dem regulären Ausdruck nacheinander mit jedem Zeichen der Zeichenkette verglichen wird. +Reguläre Ausdrücke berücksichtigen normalerweise Groß- und Kleinschreibung, sodass etwa der Ausdruck `The` nicht mit der Zeichenkette `the` übereinstimmen würde. + ++"The" => The fat cat sat on the mat. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/1paXsy/1) + +## 2. Metazeichen + +Metazeichen sind Bausteine von regulären Ausdrücken. Sie stehen nicht für sich selbst, sondern haben eine besondere Bedeutung und werden in spezieller Weise interpretiert. +Einige Metazeichen erhalten eine andere Bedeutung oder überhaupt erst eine besondere Bedeutung innerhalb eckiger Klammern `[]`. Folgende Metazeichen gibt es: + +|Metazeichen|Beschreibung| +|:----:|----| +|.|Der Punkt entspricht jedem einzelnen Zeichen, außer Zeilenumbrüchen.| +|[ ]|Zeichenklasse, entspricht jedem Zeichen innerhalb der eckigen Klammern.| +|[^ ]|Negierte Zeichenklasse, entspricht jedem Zeichen welches nicht innerhalb der eckigen Klammern definiert ist.| +|*|Entspricht 0 oder mehr Wiederholungen des vorhergehenden Teilausdrucks.| +|+|Entspricht 1 oder mehr Wiederholungen des vorhergehenden Teilausdrucks.| +|?|Macht den vorhergehenden Teilausdruck optional.| +|{n,m}|Entspricht mindestens "n", aber nicht mehr als "m" Wiederholungen des vorhergehenden Teilausdrucks.| +|(xyz)|Gruppierung, entspricht den Zeichen xyz in der exakten Reihenfolge.| +|||Alternation, entspricht entweder dem Teilausdruck vor oder nach dem \|.| +|\|Escaped das nachfolgende Zeichen. Dies ermöglicht es Zeichen zu blockieren[ ] ( ) { } . * + ? ^ $ \ |
| +|^|Entspricht dem Anfang der Eingabe.| +|$|Entspricht dem Ende der Eingabe.| + +## 2.1 Punkt + +Der Punkt `.` ist das einfachste Beispiel für ein Metazeichen. Er steht für jedes beliebiges Zeichen mit der Ausnahme von Zeilenumbrüchen/Enter-Zeichen. +Als Beispiel, der reguläre Ausdruck `.ar` bedeutet: ein beliebiges Zeichen, gefolgt von dem Buchstaben `a`, gefolgt vom Buchstaben `r`. + ++".ar" => The car parked in the garage. ++[Teste den regulären Ausdruck](https://regex101.com/r/xc9GkU/1) + +## 2.2 Zeichenklasse + +Zeichenklassen werden auch als Zeichenmengen oder -sätze bezeichnet (eng. *character set/class*). Sie werden in eckige Klammern definiert. Um eine Zeichenfolge wie `A-Z` oder `0-9` zu definieren, kann ein Bindestrich `-` verwendet werden. Die Reihenfolge sonstiger Zeichen innerhalb der eckigen Klammern spielt keine Rolle. Zum Beispiel bedeutet der reguläre Ausdruck `[Tt]he`: ein groß geschriebenes `T` oder ein kleingeschriebenes `t`, gefolgt vom Buchstaben `h` und weiter gefolgt vom Buchstaben `e`. + ++"[Tt]he" => The car parked in the garage. ++[Teste den regulären Ausdruck](https://regex101.com/r/2ITLQ4/1) + +Ein Punkt in einer Zeichenklasse bedeutet, anders als sonst, einen wörtlichen Punkt. Der reguläre Ausdruck `ar[.]` bedeutet: ein kleingeschriebenes Zeichen `a`, gefolgt vom kleingeschriebenen Buchstaben `r`, gefolgt von einem Punkt-Zeichen `.`. + ++"ar[.]" => A garage is a good place to park a car. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/wL3xtE/1) + +### 2.2.1 Negierte Zeichenklasse + +Im Allgemeinen stellt das Zirkumflex `^` den Anfang einer Zeichenkette dar. Wenn es aber nach der öffnenden eckigen Klammer gesetzt wird, dann wird die Zeichenklasse negiert (eng. *negated character set*). Als Beispiel, der reguläre Ausdruck `[^c]ar` bedeutet: ein beliebiges Zeichen außer `c`, gefolgt vom Buchstaben `a`, gefolgt vom Buchstaben `r`. + ++"[^c]ar" => The car parked in the garage. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/nNNlq3/1) + +## 2.3 Wiederholungen + +Die Metazeichen `+`, `*` und `?` bieten einen einfachen Weg, anzugeben, wie oft sich ein bestimmter Teilausdruck wiederholen soll. Sie gehören damit zu den sogenannten "Quantifizierern" (eng. *quantifier*). +Sie können sich je nach Situation unterschiedlich verhalten. + +### 2.3.1 Stern + +Das Symbol `*` stimmt mit beliebig vielen Wiederholungen des vorhergehenden Teilausdrucks überein. Der Ausdruck `a*` heißt: +null, eins oder mehrere `a`s in Folge. Da sich der Stern auf Teilausdrücke bezieht, kann er auch bspw. hinter einer Zeichenklasse stehen +und stimmt dann mit beliebig vielen Zeichen aus der Klasse in Folge überein. Zum Beispiel bedeutet der Ausdruck `[a-z]*`: eine +beliebige Anzahl von Kleinbuchstaben in Folge. + ++"[a-z]*" => The car parked in the garage #21. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/7m8me5/1) + +Das `*`-Symbol kann zusammen mit dem Metazeichen `.` verwendet werden, um mit einer vollkommen beliebigen Zeichenkette übereinzustimmen `.*`. +Es kann auch mit der vordefinierten Zeichenklasse `\s` verwendet werden, um mit beliebig viel Leerraum (Leerzeichen, Tabulatoren, Zeilenumbrüchen) +übereinzustimmen. Der Ausdruck `\s*cat\s*` heißt zum Beispiel: null oder mehrere Leerzeichen, gefolgt von dem Buchstaben `c`, gefolgt vom Buchstaben `a`, +gefolgt vom Buchstaben `t` und schließlich gefolgt von null oder mehreren Leerzeichen. + ++"\s*cat\s*" => The fat cat sat on the concatenation. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/gGrwuz/1) + +### 2.3.2 Plus + +Das `+`-Symbol stimmt mit einer oder mehr Wiederholungen des vorhergehenden Teilausdrucks überein. Der reguläre Ausdruck +`c.+t` bedeutet: Buchstabe `c`, gefolgt von mindestens einem beliebigen Zeichen, gefolgt vom Buchstaben `t`. Das `t` ist dabei +das letzte `t` in der hier zu sehenden Übereinstimmung, wobei es hier auch weitere Übereinstimmungen gäbe (siehe "Teste den regulären Ausdruck"). + ++"c.+t" => The fat cat sat on the mat. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/Dzf9Aa/1) + +### 2.3.3 Fragezeichen + +In regulären Ausdrücken sorgt das Metazeichen `?` dafür, dass der vorhergehende Teilausdruck optional wird. +Somit stimmt es mit null oder einer Übereinstimmung des Teilausdrucks überein. +Zum Beispiel heißt der reguläre Ausdruck `[T]?he`: ein oder kein `T`, gefolgt von dem Buchstaben `h`, gefolgt von dem Buchstaben `e`. + ++"[T]he" => The car is parked in the garage. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/cIg9zm/1) + ++"[T]?he" => The car is parked in the garage. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/kPpO2x/1) + +## 2.4 Geschweifte Klammern + +Geschweifte Klammern `{}` gehören wie die zuvor behandelten Metazeichen zu den Quantifizierern. Sie werden verwendet, +um genau anzugeben wie oft ein Teilausdruck minimal und maximal hintereinander übereinstimmen muss. +Zum Beispiel bedeutet der reguläre Ausdruck `[0-9]{2,3}`: Mindestens zwei, aber maximal drei Ziffern (Zeichenfolge 0-9) hintereinander. + ++"[0-9]{2,3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/juM86s/1) + +Die zweite Zahl kann ausgelassen werden. Somit heißt der Ausdruck `[0-9]{2,}`: zwei oder mehr Ziffern in Folge. +Wenn wir auch das Komma entfernen, heißt `[0-9]{3}`: genau drei Ziffern in Folge. + ++"[0-9]{2,}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/Gdy4w5/1) + ++"[0-9]{3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/Sivu30/1) + +## 2.5 Gruppierungen + +Eine Gruppierung (eng. *capturing group*) fasst eine Gruppe von Teilausdrücken in Klammern `(...)` zusammen. +Eine Gruppierung selbst ist ebenfalls ein Teilausdruck, weshalb Quantoren wie `{}`, `*` oder `?` auf sie angewendet werden können. +Zum Beispiel stimmt der reguläre Ausdruck `(ab)*` mit null oder mehr Vorkommen von `a` und `b` hintereinander überein. +Auch das "Oder"-Metazeichen `|` kann innerhalb einer Gruppierung verwendet werden. Der reguläre Ausdruck `(c|g|p)ar` bedeutet: +kleines `c`, `g` oder `p`, gefolgt vom Buchstaben `a`, gefolgt vom Buchstaben `r`. Dies ist äquivalent zu `[cgp]ar`. + ++"(c|g|p)ar" => The car is parked in the garage. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/tUxrBG/1) + +Gruppierungen stimmen nicht nur mit Zeichenketten überein, sondern "merken" sich auch die übereinstimmenden Zeichen in der Gruppe für die Verwendung in der Elternsprache +(auch Rückwärtsreferenz genannt). +Die Elternsprache kann Python, JavaScript oder sonst irgendeine Sprache sein, die reguläre Ausdrücke implementiert. + + +### 2.5.1 Gruppierungen ohne Rückwärtsreferenz + +Gruppierungen ohne Rückwärtsreferenz (eng. *non-capturing groups*) sind Gruppierungen, die nur mit den Zeichen übereinstimmen, diese aber nicht für spätere Verwendung zwischenspeichern. +Solche Gruppierungen werden mit einem `?`, gefolgt von einem `:` in Klammern `(...)` definiert. +Somit gleicht der reguläre Ausdruck `(?:c|g|p)ar` dem Ausdruck `(c|g|p)ar` in seiner Übereinstimmung mit den Zeichenketten, aber im Gegensatz erzeugt er keine Rückwärtsreferenz. + ++"(?:c|g|p)ar" => The car is parked in the garage. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/Rm7Me8/1) + +Gruppierungen ohne Rückwärtsreferenz können für Finden-und-Ersetzen oder in Kombination mit normalen Gruppierungen nützlich sein, um den Überblick zu behalten, +wenn auf Basis der Übereinstimmungen eine Ausgabe erzeugt wird. Siehe auch [4. Lookaround](#4-lookaround). + +## 2.6 Alternation + +In einem regulären Ausdruck wird der Trennstrich `|` verwendet, um Alternativen (eng. *alternation*) zu definieren. +Alternation ist wie ein "ODER" zwischen mehreren Teilausdrücken. Nun könnte man annehmen, dass +Zeichenklassen und Alternation auf die gleiche Art und Weise funktionieren. Aber der große Unterschied +zwischen diesen beiden ist, dass Zeichenklassen für einzelne Zeichen funktionieren, während für Alternationen +beliebige Teilausdrücke verwendet werden können. So heißt der reguläre Ausdruck `(T|t)he|car` beispielsweise: +Entweder ein großes `T` oder kleines `t`, dann der Buchstabe `h` gefolgt vom Buchstaben `e` ODER +`c`, gefolgt von `a`, gefolgt von `r`. Man beachte die Klammern, die zur Trennung der einen Alternation von der anderen +gesetzt wurden. + ++"(T|t)he|car" => The car is parked in the garage. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/fBXyX0/1) + +## 2.7 Escaping + +Der Backslash `\` wird in regulären Ausdrücken verwendet, um die besondere Bedeutung des folgenden Zeichens aufzuheben (eng. *escape*) oder ihm eine besondere Bedeutung zu verleihen +(s. [Vordefinierte Zeichenklassen](#3-vordefinierte-zeichenklassen)). +Er erlaubt es, für andere Zwecke reservierte Zeichen wie die Metazeichen `{ } [ ] / \ + * . $ ^ | ?` als Literale, also wörtliche Übereinstimmungen zu nutzen. +Um mit einem besonderen Zeichen wortwörtlich übereinzustimmen, muss es auf ein `\` folgen. + +Der reguläre Ausdruck `.` zum Beispiel wird benutzt, um mit einem beliebigen Zeichen übereinzustimmen. +Der Ausdruck `(f|c|m)at\.?` hebt diese Bedeutung auf: `f`, `c` oder `m`, gefolgt von `a`, gefolgt von `t`, schließlich gefolgt von einem optionalen `.`. + ++"(f|c|m)at\.?" => The fat cat sat on the mat. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/DOc5Nu/1) + +## 2.8 Anker + +In regulären Audrücken werden Anker (eng. *anchor*) verwendet, um zu überprüfen, ob der Teilausdruck mit dem +Anfang oder dem Ende der Teilausgabe übereinstimmt. Es gibt zwei Arten von Ankern: das Zirkumflex `^` +stimmt mit dem Anfang, das Dollarzeichen `$` mit dem Ende der Eingabe überein. + +### 2.8.1 Zirkumflex + +Das Zirkumflex `^` (eng. *caret*) wird benutzt um zu überprüfen, ob der Teilausdruck mit dem Anfang der Zeichenkette übereinstimmt. +Wenn wir den regulären Ausdruck `^a` auf die Eingabe `abc` anwenden, stimmt er mit `a` überein. +Aber wenn wir auf die gleiche Eingabe den Ausdruck `^b` anwenden, gibt es keine Übereinstimmungen, weil in der Zeichenkette `abc` kein "b" +am Anfang steht. Schauen wir uns einen anderen Ausdruck an: `^(T|t)he`. Dieser bedeutet: kleines `t` oder großes `T` am Anfang der Eingabe, +gefolgt von `h`, gefolgt von `e`. + ++"(T|t)he" => The car is parked in the garage. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/5ljjgB/1) + ++"^(T|t)he" => The car is parked in the garage. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/jXrKne/1) + +### 2.8.2 Dollar + +Das Dollarzeichen `$` wird benutzt um zu überprüfen, ob der Teilausdruck mit dem Ende der Zeichenkette übereinstimmt. +Der reguläre Ausdruck `(at\.)$` etwa bedeutet: `a`, gefolgt von `t` und dann `.` am Ende der Eingabe. + ++"(at\.)" => The fat cat. sat. on the mat. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/y4Au4D/1) + ++"(at\.)$" => The fat cat. sat. on the mat. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/t0AkOd/1) + +## 3. Vordefinierte Zeichenklassen + +Reguläre Ausdrücke haben Kürzel für die am häufigsten benötigten Zeichenklassen, was viele Ausdrücke vereinfacht und kürzer macht. +Das sind die vordefinierten Zeichenklassen: + +|Shorthand|Description| +|:----:|----| +|.|Beliebiges Zeichen außer Zeilenumbruch| +|\w|Stimmt mit alphanumerischen Zeichen überein: `[a-zA-Z0-9_]`| +|\W|Stimmt mit nicht-alphanumerischen Zeichen überein: `[^\w]`| +|\d|Stimmt mit Ziffern überein: `[0-9]`| +|\D|Stimmt mit Zeichen, die keine Ziffern sind überein: `[^\d]`| +|\s|Stimmt mit Leerraum überein: `[\t\n\f\r\p{Z}]`| +|\S|Stimmt mit allem außer Leerraum überein: `[^\s]`| + +## 4. Umsehen (Lookaround) + +Lookbehind ("zurückschauen") und Lookahead ("vorausschauen") (auch Lookaround ("Umsehen") genannt) sind besondere Arten von **Gruppierungen ohne Rückwärtsreferenz** +(zur Erinnerung: das sind Gruppierungen, die zwar mit dem Muster übereinstimmen, aber sich die Übereinstimmung nicht "merken"). +Sie werden in Situationen verwendet, wo wir ein Muster einfangen wollen, dem andere Muster folgen oder vorhergehen. +Zum Beispiel wollen wir alle Zahlen aus der Zeichenkette `$4.44 and $10.88`, vor denen ein Dollarzeichen `$` steht. Wir benutzen dafür den folgenden regulären Audruck: +`(?<=\$)[0-9.]*`. Das heißt: Stimme mit allen Zeichenketten überein, die Ziffern `0-9` oder Punkte `.` enthalten und die einem Dollarzeichen `$` folgen. + +Das sind die Lookarounds, die es gibt: + +|Symbol|Name| +|:----:|----| +|?=|Positiver Lookahead| +|?!|Negativer Lookahead| +|?<=|Positiver Lookbehind| +|? +"(T|t)he(?=\sfat)" => The fat cat sat on the mat. ++"(T|t)he(?!\sfat)" => The fat cat sat on the mat. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/V32Npg/1) + +### 4.3 Positives Zurückschauen (Lookbehind) + +Positive Lookbehinds werden verwendet, um alle Übereinstimmungen in einer Zeichenkette zu bekommen, denen ein bestimmtes Muster vorhergeht. +Postive Lookbehinds werden mit `(?<=...)` notiert. Der reguläre Ausdruck `(?<=(T|t)he\s)(fat|mat)` zum Beispiel bedeutet: alle `fat` oder `mat`, +die nach `The ` oder `the ` kommen, stimmen überein. + ++"(?<=(T|t)he\s)(fat|mat)" => The fat cat sat on the mat. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/avH165/1) + +### 4.4 Negativer Lookbehind + +Negative Lookbehinds werden verwendet, um alle Übereinstimmungen in einer Zeichenkette zu bekommen, denen **nicht** ein bestimmtes Muster vorhergeht. +Negative Lookbehinds werden mit `(? +"(?<!(T|t)he\s)(cat)" => The cat sat on cat. ++"The" => The fat cat sat on the mat. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/dpQyf9/1) + ++"/The/gi" => The fat cat sat on the mat. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/ahfiuh/1) + +### 5.2 Globale Suche + +Der `g` Modifikator wird benutzt, um eine globale Suche durchzuführen (alle Übereinstimmungen finden, nicht nach der ersten aufhören). +Zum Beispiel heißt der reguläre Ausdruck `/.(at)/g`: ein beliebiges Zeichen (außer Zeilenumbruch), gefolgt von `a`, gefolgt von `t`. +Weil wir den `g` Modifikator angegeben haben, findet der reguläre Ausdruck nun alle Übereinstimmungen in der Eingabe, nicht nur die erste +(was das Standardverhalten ist). + ++"/.(at)/" => The fat cat sat on the mat. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/jnk6gM/1) + ++"/.(at)/g" => The fat cat sat on the mat. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/dO1nef/1) + +### 5.3 Mehrzeilig + +Der `m` Modifikator wird benutzt, um eine mehrzeilige Suche durchzuführen. Wie zuvor erwähnt werden Anker `(^, $)` genutzt, um zu überprüfen, +ob ein Muster dem Anfang oder dem Ende der Eingabe entspricht. Wenn wir stattdessen wollen, dass Anker zeilenweise funktionieren, nutzen wir den `m` +Modifikator. Zum Beispiel bedeutet der reguläre Ausdruck `/at(.)?$/gm`: `a`, gefolgt von `t`, dann optional ein beliebiges Zeichen außer +Zeilenumbruch. Wegen des `m` Modifikators wird das Muster nun auf das Ende jeder Zeile statt nur das Ende der gesamten Eingabe angewandt. + ++"/.at(.)?$/" => The fat + cat sat + on the mat. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/hoGMkP/1) + ++"/.at(.)?$/gm" => The fat + cat sat + on the mat. ++ +[Teste den regulären Ausdruck](https://regex101.com/r/E88WE2/1) + +## 6. Gierige vs. faule Übereinstimmung + +Standardmäßig finden reguläre Ausdrücke Übereinstimmungen mit Gier (eng. *greed*), d.h. es wird nach den längsten Übereinstimmungen gesucht. +Mit `?` können wir faul (eng. *lazy*) suchen, d.h. es wird nach den kürzesten Übereinstimmungen gesucht. + ++"/(.*at)/" => The fat cat sat on the mat. ++ + +[Teste den regulären Ausdruck](https://regex101.com/r/AyAdgJ/1) + ++"/(.*?at)/" => The fat cat sat on the mat. ++ + +[Teste den regulären Ausdruck](https://regex101.com/r/AyAdgJ/2) + +## Beitragen + +* Öffne Pull Requests mit Verbesserungen +* Diskutiere Ideen in Issues +* Erzähl es anderen +* Gib Rückmeldung [](https://twitter.com/ziishaned) + +## Lizenz + +MIT © [Zeeshan Ahmad](https://twitter.com/ziishaned) diff --git a/translations/README-es.md b/translations/README-es.md new file mode 100644 index 00000000..7c3fab7f --- /dev/null +++ b/translations/README-es.md @@ -0,0 +1,489 @@ ++
+ + + +## Traducciones: + +* [English](../README.md) +* [German](../translations/README-de.md) +* [Español](../translations/README-es.md) +* [Français](../translations/README-fr.md) +* [Português do Brasil](../translations/README-pt_BR.md) +* [中文版](../translations/README-cn.md) +* [日本語](../translations/README-ja.md) +* [한국어](../translations/README-ko.md) +* [Turkish](../translations/README-tr.md) +* [Greek](../translations/README-gr.md) +* [Magyar](../translations/README-hu.md) +* [Polish](../translations/README-pl.md) +* [Русский](../translations/README-ru.md) +* [Tiếng Việt](../translations/README-vn.md) +* [فارسی](../translations/README-fa.md) +* [עברית](../translations/README-he.md) + +## Qué es una expresión regular? + +[](https://gum.co/learn-regex) + +> Una expresión regular es un grupo de caracteres o símbolos, los cuales son usados para buscar un patrón específico dentro de un texto. + +Una expresión regular es un patrón que que se compara con una cadena de caracteres de izquierda a derecha. La palabra "expresión regular" puede también ser escrita como "Regex" o "Regexp". Las expresiones regulares se utilizan para reemplazar un texto dentro de una cadena de caracteres (*string*), validar formularios, extraer una porción de una cadena de caracteres (*substring*) basado en la coincidencia de un patrón, y muchas cosas más. + +Imagina que estás escribiendo una aplicación y quieres agregar reglas para cuando el usuario elija su nombre de usuario. Nosotros queremos permitir que el nombre de usuario contenga letras, números, guion bajo (raya), y guion medio. También queremos limitar el número de caracteres en el nombre de usuario para que no se vea feo. Para ello, usamos la siguiente expresión regular para validar el nombre de usuario. + +
+ ++ +
+
++
+ +La expresión regular anterior puede aceptar las cadenas `john_doe`, `jo-hn_doe` y `john12_as`. Sin embargo, la expresión no coincide con el nombre de usuario `Jo` porque es una cadena de caracteres que contiene letras mayúsculas y es demasiado corta. + +## Tabla de contenido + +- [Introducción](#1-introducción) +- [Meta-caracteres](#2-meta-caracteres) + - [Full stop](#21-full-stop) + - [Conjunto de caracteres](#22-conjunto-de-caracteres) + - [Conjunto de caracteres negados](#221-conjunto-de-caracteres-negado) + - [Repeticiones](#23-repeticiones) + - [Asterisco](#231-asterisco) + - [Signo más](#232-signo-de-más) + - [Signo de interrogación](#233-signo-de-interrogación) + - [Llaves](#24-llaves) + - [Grupos de caracteres](#25-grupos-de-caracteres) + - [Alternancia](#26-alternancia) + - [Caracteres especiales de escape](#27-caracteres-especiales-de-escape) + - [Anclas](#28-anclas) + - [Símbolo de intercalación](#281-símbolo-de-intercalación) + - [Símbolo del dólar](#282-símbolo-del-dólar) +- [Conjunto de caracteres abreviados](#3-conjunto-de-caracteres-abreviados) +- [Mirar alrededor](#4-mirar-alrededor) + - [Mirar hacia delante positivo](#41-mirar-hacia-adelate-positivo) + - [Mirar hacia delante negativo](#42-mirar-hacia-delaten-negativo) + - [Mirar hacia atrás positivo](#43-mirar-hacia-atras-positivo) + - [Mirar hacia atrás negativo](#44-mirar-hacia-atras-negativo) +- [Indicadores](#5-indicadores) + - [Mayúsculas y minúsculas](#51-mayúsculas-y-minúsculas) + - [Búsqueda global](#52-búsqueda-global) + - [Multilínea](#53-multilínea) + + +## 1. Introducción + +Una expresión regular es sólo un patrón de caracteres que utilizamos para realizar búsquedas en un texto. Por ejemplo, la expresión regular `the` significa: la letra `t`, seguida de la letra `h`, seguida de la letra `e`. + ++
+"the" => The fat cat sat on the mat. ++ +[Prueba la expresión regular](https://regex101.com/r/dmRygT/1) + +La expresión regular `123` coincide con la cadena `123`. La expresión regular se compara con una cadena de entrada al comparar cada carácter de la expresión regular con cada carácter de la cadena de entrada, uno tras otro. Las expresiones regulares son normalmente sensibles a mayúsculas y minúsculas, por lo que la expresión regular `The` no coincide con la cadena `the`. + ++"The" => The fat cat sat on the mat. ++ +[Prueba la expresión regular](https://regex101.com/r/1paXsy/1) + +## 2. Meta-caracteres + +Los meta-caracteres son los bloques de construcción de las expresiones regulares. Los meta-caracteres no se trabajan por sí mismos, sino que se interpretan de alguna manera especial. Algunos meta-caracteres tienen un significado especial y se escriben entre corchetes. Los meta-caracteres son los siguientes: + +|Meta-carácter|Descripción| +|:----:|----| +|.|Punto: Coincide con cualquier carácter excepto un salto de línea.| +|[ ]|Clase de caracteres: Coincide con cualquier carácter contenido entre corchetes.| +|[^ ]|Clase de caracteres negados: Coincide con cualquier carácter que no está contenido dentro de los corchetes.| +|*|Asterisco: Corresponde con 0 o más repeticiones del símbolo precedente.| +|+|Signo de más: Corresponde con 1 o más repeticiones del símbolo precedente.| +|?|Signo de interrogación: Hace que el símbolo precedente sea opcional.| +|{n,m}|Llaves: Corresponde al menos "n" pero no más de "m" repeticiones del símbolo precedente.| +|(xyz)|Grupo de caracter: Hace coincidir los caracteres xyz en ese orden exacto.| +|||Alternancia: Corresponde a los caracteres anteriores o los caracteres después del símbolo.| +|\|Escapa el siguiente carácter: Esto le permite hacer coincidir los caracteres reservados[ ] ( ) { } . * + ? ^ $ \ |
| +|^|Acento circunflejo: Hace coincidir el principio de la entrada.| +|$|Símbolo de dólar: Corresponde al final de la entrada.| + +## 2.1 Full stop + +Full stop `.` es el ejemplo más simple del meta-carácter. El meta-carácter `.` coincide con cualquier carácter. No coincidirá con el retorno o nuevos caracteres de línea. Por ejemplo, la expresión regular `.ar` significa: cualquier carácter, seguido del carácter `a`, seguido del carácter `r`. + ++".ar" => The car parked in the garage. ++ +[Prueba la expresión regular](https://regex101.com/r/xc9GkU/1) + +## 2.2 Conjunto de caracteres + +Los conjuntos de caracteres también se llaman clase de caracteres. Los corchetes se utilizan para especificar conjuntos de caracteres. Utilice un guion dentro de un conjunto de caracteres para especificar el rango de los caracteres. El orden del rango de caracteres dentro de corchetes no importa. Por ejemplo, la expresión regular `[Tt]he` significa: un carácter en mayúscula `T` o minúscula `t`, seguido del carácter `h`, seguido del carácter `e`. + ++"[Tt]he" => The car parked in the garage. ++ +[Prueba la expresión regular](https://regex101.com/r/2ITLQ4/1) + +Sin embargo, un período dentro de un conjunto de caracteres significa un período literal. La expresión regular `ar[.]` significa: un carácter en minúscula `a`, seguido del carácter `r`, seguido del carácter `.`. + ++"ar[.]" => A garage is a good place to park a car. ++ +[Prueba la expresión regular](https://regex101.com/r/wL3xtE/1) + +### 2.2.1 Conjunto de caracteres negados + +En general, el símbolo de intercalación representa el comienzo de la cadena, pero cuando se escribe después del corchete de apertura niega el conjunto de caracteres. Por ejemplo, la expresión regular `[^c]ar` significa: cualquier carácter, excepto `c`, seguido del carácter `a`, seguido del carácter `r`. + ++"[^c]ar" => The car parked in the garage. ++ +[Prueba la expresión regular](https://regex101.com/r/nNNlq3/1) + +## 2.3 Repeticiones + +Los siguientes caracteres meta `+`, `*` o `?`, se utilizan para especificar cuántas veces puede producirse un subpatrón. Estos meta-caracteres actúan de manera diferente en diferentes situaciones. + +### 2.3.1 Asterisco + +El símbolo `*` coincide con cero o más repeticiones del marcador anterior. La expresión regular `a*` significa: cero o más repeticiones del carácter en minúscula precedente `a`. Pero, si aparece después de un conjunto de caracteres o una clase, entonces encuentra las repeticiones de todo el conjunto de caracteres. Por ejemplo, la expresión regular `[a-z]*` significa: cualquier número de letras minúsculas en una fila. + ++"[a-z]*" => The car parked in the garage #21. ++ +[Prueba la expresión regular](https://regex101.com/r/7m8me5/1) + +El símbolo `*` se puede utilizar con el meta-carácter `.` para que coincida con cualquier cadena de caracteres `.*`. El símbolo `*` se puede utilizar con el carácter de espacio en blanco `\s` para que coincida con una cadena de caracteres de espacio en blanco. Por ejemplo, la expresión `\s*cat\s*` significa: cero o más espacios, seguido por el carácter en minúscula `c`, seguido del carácter en minúscula `a`, seguido del carácter en minúscula `t`, seguido de cero o más espacios. + ++"\s*cat\s*" => The fat cat sat on the concatenation. ++ +[Prueba la expresión regular](https://regex101.com/r/gGrwuz/1) + +### 2.3.2 Signo de más + +El símbolo `+` coincide con una o más repeticiones del carácter anterior. Por ejemplo, la expresión regular `c.+T` significa: carácter en minúscula `c`, seguido por lo menos de un carácter, luego el carácter en minúscula `t`. + ++"c.+t" => The fat cat sat on the mat. ++ +[Prueba la expresión regular](https://regex101.com/r/Dzf9Aa/1) + +### 2.3.3 Signo de interrogación + +En expresiones regulares el meta-carácter `?` hace que el carácter precedente sea opcional. Este símnbolo coincide con cero o una instancia del carácter precedente. Por ejemplo, la expresión regular `[T]?he` significa: El carácter opcional `T` seguido por el carácter en minúscula `h`, seguido del carácter en minúscula `e`. + ++"[T]he" => The car is parked in the garage. ++ +[Prueba la expresión regular](https://regex101.com/r/cIg9zm/1) + ++"[T]?he" => The car is parked in the garage. ++ +[Prueba la expresión regular](https://regex101.com/r/kPpO2x/1) + +## 2.4 Llaves + +En la expresión regular, las llaves, que también se denominan cuantificadores, son utilizados para especificar el número de veces que se puede repetir un carácter o un grupo de caracteres. Por ejemplo, la expresión regular `[0-9]{2,3}` significa: Combina al menos 2 dígitos pero no más de 3 (caracteres en el rango de 0 a 9). + ++"[0-9]{2,3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Prueba la expresión regular](https://regex101.com/r/juM86s/1) + +Podemos dejar fuera el segundo número. Por ejemplo, la expresión regular `[0-9] {2,}` significa: Combina 2 o más dígitos. Si también eliminamos la coma, la expresión regular `[0-9]{3}` significa: coincidir exactamente con 3 dígitos. + ++"[0-9]{2,}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Prueba la expresión regular](https://regex101.com/r/Gdy4w5/1) + ++"[0-9]{3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Prueba la expresión regular](https://regex101.com/r/Sivu30/1) + +## 2.5 Grupos de caracteres + +Un grupo de caracteres es un grupo de sub-patrones que se escribe dentro de paréntesis `(...)`. Como hemos discutido antes en la expresión regular, si ponemos un cuantificador después de un carácter, repetiremos el carácter anterior. Pero si ponemos un cuantificador después de un grupo de caracteres, entonces repetimos todo el grupo de caracteres. Por ejemplo, la expresión regular `(ab)*` coincide con cero o más repeticiones del caracter `ab`. También podemos usar el carácter de alternancia `|` meta dentro del grupo de caracteres. Por ejemplo, la expresión regular `(c|g|p)ar` significa: carácter en minúscula `c`, `g` o `p`, seguido del carácter `a`, seguido del carácter `r`. ++"(c|g|p)ar" => The car is parked in the garage. ++ +[Prueba la expresión regular](https://regex101.com/r/tUxrBG/1) + +## 2.6 Alternancia + +En la expresión regular, la barra vertical `|` se utiliza para definir la alternancia. La alternancia es como una condición entre múltiples expresiones. Ahora, puedes estar pensando que el conjunto de caracteres y la alternancia funciona de la misma manera. Sin embargo, la gran diferencia entre el conjunto de caracteres y la alternancia es que el conjunto de caracteres funciona a nivel de carácter pero la alternancia funciona a nivel de expresión. Por ejemplo, la expresión regular `(T|t)he|car` significa: el carácter en mayúscula `T` o en minúscula `t`, seguido del carácter en minúscula `h`, seguido del carácter en minúscula `e` o del carácter en minúscula `c`, seguido de un carácter en minúscula `a`, seguido del carácter en minúscula `r`. + ++"(T|t)he|car" => The car is parked in the garage. ++ +[Prueba la expresión regular](https://regex101.com/r/fBXyX0/1) + +## 2.7 Caracteres especiales de escape + +La barra invertida `\` se utiliza en la expresión regular para escapar el carácter siguiente. Esto permite especificar un símbolo como un carácter coincidente incluyendo caracteres reservados `{}[]/\+*.^|?`. Para usar un carácter especial como un carácter coincidente, agrega `\` a su izquierda. + +Por ejemplo, la expresión regular `.` se utiliza para coincidir con cualquier carácter, excepto la nueva línea. Ahora, para emparejar `.` en una cadena de entrada, la expresión regular `(f|c|m)at\.?` significa: el carácter en minúscula `f`, `c` o `m`, seguido del carácter en minúscula `a`, seguido del carácter en minúscula `t`, seguido del carácter opcional `.`. + ++"(f|c|m)at\.?" => The fat cat sat on the mat. ++ +[Prueba la expresión regular](https://regex101.com/r/DOc5Nu/1) + +## 2.8 Anclas + +En expresiones regulares, usamos anclas para comprobar si el símbolo coincidente es el símbolo inicial o el símbolo final de la cadena de entrada. Los anclajes son de dos tipos: El primer tipo es el símbolo de intercalación `^` que comprueba si el carácter coincidente es el carácter inicial de la entrada y el segundo tipo es el símbolo del dólar `$` que comprueba si el carácter coincidente es el último carácter de la cadena de entrada. + +### 2.8.1 Símbolo de intercalación + +El símbolo de intercalación `^` se usa para verificar si el carácter coincidente es el primer carácter de la cadena de entrada. Si aplicamos la siguiente expresión regular `^a` (si `a` es el símbolo inicial) a la cadena de entrada, `abc` coincide con `a`. Pero si aplicamos la expresión regular `^b` en la cadena de entrada anterior, no coincide con nada. Porque en la cadena de entrada `abc`, `b` no es el símbolo inicial. Vamos a echar un vistazo a la expresión regular `^(T|t)he` que significa: carácter en mayúscula `T` o carácter en minúscula `t` es el símbolo inicial de la cadena de entrada, seguido del carácter minúscula `h` y seguido del carácter en minúscula `e`. + ++"(T|t)he" => The car is parked in the garage. ++ +[Prueba la expresión regular](https://regex101.com/r/5ljjgB/1) + ++"^(T|t)he" => The car is parked in the garage. ++ +[Prueba la expresión regular](https://regex101.com/r/jXrKne/1) + +### 2.8.2 Símbolo del dólar + +El símbolo del dólar `$` se utiliza para comprobar si el carácter coincidente es el último carácter de la cadena de entrada. Por ejemplo, la expresión regular `(at\.)$` significa: un carácter en minúscula `a`, seguido del carácter en minúscula `t`, seguido de un carácter `.` y el marcador debe ser el final de la cadena. + ++"(at\.)" => The fat cat. sat. on the mat. ++ +[Prueba la expresión regular](https://regex101.com/r/y4Au4D/1) + ++"(at\.)$" => The fat cat. sat. on the mat. ++ +[Pueba la expresión regular](https://regex101.com/r/t0AkOd/1) + +## 3. Conjunto de caracteres abreviados + +La expresión regular proporciona abreviaturas para los conjuntos de caracteres +comúnmente utilizados, que ofrecen abreviaturas convenientes para expresiones +regulares de uso común. Los conjuntos de caracteres abreviados son los siguientes: + +|Abreviatura|Descripción| +|:----:|----| +|.|Cualquier carácter excepto nueva línea| +|\w|Coincide con los caracteres alfanuméricos: `[a-zA-Z0-9_]`| +|\W|Coincide con los caracteres no alfanuméricos: `[^\w]`| +|\d|Coincide con los dígitos: `[0-9]`| +|\D|Coincide con los no dígitos: `[^\d]`| +|\s|Coincide con los caracteres espaciales: `[\t\n\f\r\p{Z}]`| +|\S|Coincide con los caracteres no espaciales: `[^\s]`| + +## 4. Mirar alrededor + +Mirar hacia delante (lookahead) y mirar hacia atrás (lookbehind), a veces conocidos +como lookaround, son tipo específico de **grupo que no captura** (Utilizados para +coincidir con el patrón pero no se incluyen en la lista correspondiente). Los +lookaheads se usan cuando tenemos la condición de que este patrón es precedido o +seguido por otro patrón determinado. Por ejemplo, queremos obtener todos los números +que están precedidos por el carácter `$` de la siguiente cadena de entrada +`$4.44 y $10.88`. Usaremos la siguiente expresión regular `(?<=\$)[0-9\.] *`, +esto significa: obtener todos los números que contienen el carácter `.` y +están precedidos del carácter `$`. A continuación se muestran los lookarounds +que se utilizan en expresiones regulares: + +|Símbolo|Descripción| +|:----:|----| +|?=|Lookahead Positivo| +|?!|Lookahead Negativo| +|?<=|Lookbehind Positivo| +|?<\!|Lookbehind Negativo| + +## 4.1 Mirar hacia adelate positivo + +El lookahead positivo afirma que la primera parte de la expresión debe ser +seguida por la expresión lookahead. La coincidencia devuelta sólo contiene el texto que +coincide con la primera parte de la expresión. Para definir un lookahead positivo, +se utilizan paréntesis. Dentro de esos paréntesis, un signo de interrogación con +signo igual se utiliza de esta manera: `(?= ...)`. La expresión de Lookahead se +escribe después del signo igual dentro de los paréntesis. Por ejemplo, la +expresión regular `[T|t]he (?=\Sfat)` significa: opcionalmente emparejar +el carácter en minúscula `t` o el carácter en mayúscula `T`, seguida del carácter `h`, seguida +del carácter `e`. Entre paréntesis definimos el lookahead positivo que indica al motor +de expresión regular que coincida con `The` o `the` seguido de la palabra `fat`. + ++"[T|t]he(?=\sfat)" => The fat cat sat on the mat. ++ +[Prueba la expresión regular](https://regex101.com/r/IDDARt/1) + +### 4.2 Mirar hacia adelate negativo + +El lookahead negativo se usa cuando necesitamos obtener todas las coincidencias +de la cadena de entrada que no son seguidas por un patrón. El aspecto negativo se +define de la misma manera que definimos el aspecto positivo, pero la única diferencia +es que en lugar del carácter igual `=` utilizamos carácter negación `!` , es decir, +`(?! ...)`. Vamos a echar un vistazo a la siguiente expresión regular `[T|t]he(?!\Sfat)` +que significa: obtener todas las `The` o `the` seguidos por la palabra `fat` precedido por un carácter de espacio. + + ++"[T|t]he(?!\sfat)" => The fat cat sat on the mat. ++ +[Prueba la expresión](https://regex101.com/r/V32Npg/1) + +### 4.3 Mirar hacia atras positivo + +Positivo lookbehind se utiliza para obtener todos los caracteres que están precedidos +por un patrón específico. La apariencia positiva se denotar por `(?<=...)`. +Por ejemplo, la expresión regular `(? <= [T|t]he\s)(fat|mat)` significa: obtener todas las palabras +`fat` o `mat` de la cadena de entrada después de la palabra `The` o `the`. + ++"(?<=[T|t]he\s)(fat|mat)" => The fat cat sat on the mat. ++ +[Prueba la expresión regular](https://regex101.com/r/avH165/1) + +### 4.4 Mirar hacia atras negativo + +El lookbehind negativo se utiliza para obtener todas las coincidencias que no +están precedidas por un patrón específico. El lookbehind negativo se denota por +`(? +"(?<![T|t]he\s)(cat)" => The cat sat on cat. ++"The" => The fat cat sat on the mat. ++ +[Prueba la expresión regularn](https://regex101.com/r/dpQyf9/1) + ++"/The/gi" => The fat cat sat on the mat. ++ +[Prueba la expresión regular](https://regex101.com/r/ahfiuh/1) + +### 5.2 Búsqueda global + +El modificador `g` se utiliza para realizar una coincidencia global +(encontrar todos las coincidencias en lugar de detenerse después de la primera coincidencia). +Por ejemplo, la expresión regular `/.(At)/g` significa: cualquier carácter, +excepto la nueva línea, seguido del carácter en minúscula `a`, seguido del carácter +en minúscula `t`. Debido a que proveimos el indicador `g` al final de la expresión +regular, ahora encontrará todas las coincidencias de toda la cadena de entrada, no sólo la +primera instancia (el cual es el comportamiento normal). + + ++"/.(at)/" => The fat cat sat on the mat. ++ +[Prueba la expresión regular](https://regex101.com/r/jnk6gM/1) + ++"/.(at)/g" => The fat cat sat on the mat. ++ +[Prueba la expresión regular](https://regex101.com/r/dO1nef/1) + +### 5.3 Multilínea + +El modificador `m` se utiliza para realizar una coincidencia de varias líneas. +Como analizamos anteriormente, las anclas `(^,$)` se utilizan para comprobar si +el patrón es el comienzo de la entrada o el final de la cadena de entrada. Pero +si queremos que las anclas funcionen en cada línea usamos el indicador `m`. +Por ejemplo, la expresión regular `/at(.)?$/Gm` significa: carácter en minúscula `a`, seguido del carácter en minúscula `t`, +opcionalmente cualquier cosa menos la nueva línea. Y debido al indicador `m`, ahora +el motor de expresión regular coincide con el patrón al final de cada línea de una cadena. + ++"/.at(.)?$/" => The fat + cat sat + on the mat. ++ +[Prueba la expresión regular](https://regex101.com/r/hoGMkP/1) + ++"/.at(.)?$/gm" => The fat + cat sat + on the mat. ++ +[Prueba la expresión regular](https://regex101.com/r/E88WE2/1) + +## Contribución + +* Reporta un problema +* Abre un pull request con mejoras +* Pasa la palabra +* Contáctame directamente a ziishaned@gmail.com o [](https://twitter.com/ziishaned) + +## Licencia + +MIT © [Zeeshan Ahmad](https://twitter.com/ziishaned) diff --git a/translations/README-fa.md b/translations/README-fa.md new file mode 100644 index 00000000..362ecec2 --- /dev/null +++ b/translations/README-fa.md @@ -0,0 +1,613 @@ ++
+ + +## برگردان ها: + +* [English](../README.md) +* [German](../translations/README-de.md) +* [Español](../translations/README-es.md) +* [Français](../translations/README-fr.md) +* [Português do Brasil](../translations/README-pt_BR.md) +* [中文版](../translations/README-cn.md) +* [日本語](../translations/README-ja.md) +* [한국어](../translations/README-ko.md) +* [Turkish](../translations/README-tr.md) +* [Greek](../translations/README-gr.md) +* [Magyar](../translations/README-hu.md) +* [Polish](../translations/README-pl.md) +* [Русский](../translations/README-ru.md) +* [Tiếng Việt](../translations/README-vn.md) +* [فارسی](../translations/README-fa.md) +* [עברית](../translations/README-he.md) + +
+ ++ +
++ +## عبارت منظم چیست؟ ++ +[](https://gum.co/learn-regex) + ++ +> عبارت منظم یک گروه از کارکترها یا نمادهاست که برای پیدا کردن یک الگوی مشخص در یک متن به کار گرفته می شود. ++ ++یک عبارت منظم یک الگو است که با رشته ای حاص مطابقت دارد. عبارت منظم در اعتبار سنجی داده های ورودی فرم ها، پیدا کردن یک زیر متن در یک متن بزرگتر بر اساس یک الگوی ویژ] و مواردی از این دست به کار گرفته می شود. عبارت "Regular expression" کمی ثقیل است، پس معمولا بیشتر مخفف آن - "regex" یا "regexp" - را به کار می برند. + +فرض کنید یه برنامه نوشته اید و می خواهید قوانینی برای گزینش نام کاربری برا کاربران بگزارید. می خواهیم اجازه دهی که نام کاربری شامل حروف، اعداد، خط زیر و خط فاصله باشد. همچنین می خواهیم تعداد مشخصه ها یا همان کارکترها در نام کاربری محدود کنیم . ما از چنین عبارت منظمی برای اعتبار سنجی نام کاربری استفاده می کنیم: ++
++
++
+عبارت منظم به کار رفته در اینجا رشته `john_doe` و `jo-hn_doe` و `john12_as` می پذیرد ولی `Jo` را به دلیل کوتاه بودن بیش از حد و همچنین به کار بردن حروف بزرگ نمی پذیرد. +++ +## فهرست + +- [پایه ای ترین همخوانی](#1-basic-matchers) +- [Meta character](#2-meta-characters) + - [Full stop](#21-full-stop) + - [Character set](#22-character-set) + - [Negated character set](#221-negated-character-set) + - [Repetitions](#23-repetitions) + - [The Star](#231-the-star) + - [The Plus](#232-the-plus) + - [The Question Mark](#233-the-question-mark) + - [Braces](#24-braces) + - [Character Group](#25-character-group) + - [Alternation](#26-alternation) + - [Escaping special character](#27-escaping-special-character) + - [Anchors](#28-anchors) + - [Caret](#281-caret) + - [Dollar](#282-dollar) +- [Shorthand Character Sets](#3-shorthand-character-sets) +- [Lookaround](#4-lookaround) + - [Positive Lookahead](#41-positive-lookahead) + - [Negative Lookahead](#42-negative-lookahead) + - [Positive Lookbehind](#43-positive-lookbehind) + - [Negative Lookbehind](#44-negative-lookbehind) +- [Flags](#5-flags) + - [Case Insensitive](#51-case-insensitive) + - [Global search](#52-global-search) + - [Multiline](#53-multiline) +- [Greedy vs lazy matching](#6-greedy-vs-lazy-matching) +++ +## 1. پایه ای ترین همخوانی + +یک عبارت منظم در واقع یک الگو برای جست و جو در یک متن است. برای مثال عبارت منظم `the` به معنی : حرف +`t`, پس از آن حرف `h`, پس از آن حرف `e` است. +++"the" => The fat cat sat on the mat. ++ ++ +[عبارت منظم را در عمل ببینید](https://regex101.com/r/dmRygT/1) + +عبارت منظم `123` با رشته `123` مطابقت دارد. عبارت منظم با مقایسه حرف به حرف و کارکتر به کارکترش با متن مورد نظر تطابق را می یابد. همچنین عبارت منظم حساس به اندازه (بزرگی یا کوچکی حروف) هستند. بنابر این واژه ی `The` با `the` همخوان نیست. ++ ++"The" => The fat cat sat on the mat. ++ ++ +[این عبارت منظم را در عمل ببنیند](https://regex101.com/r/1paXsy/1) ++ +## 2. Meta Characters + +Meta characters are the building blocks of the regular expressions. Meta +characters do not stand for themselves but instead are interpreted in some +special way. Some meta characters have a special meaning and are written inside +square brackets. The meta characters are as follows: + +|Meta character|Description| +|:----:|----| +|.|Period matches any single character except a line break.| +|[ ]|Character class. Matches any character contained between the square brackets.| +|[^ ]|Negated character class. Matches any character that is not contained between the square brackets| +|*|Matches 0 or more repetitions of the preceding symbol.| +|+|Matches 1 or more repetitions of the preceding symbol.| +|?|Makes the preceding symbol optional.| +|{n,m}|Braces. Matches at least "n" but not more than "m" repetitions of the preceding symbol.| +|(xyz)|Character group. Matches the characters xyz in that exact order.| +|||Alternation. Matches either the characters before or the characters after the symbol.| +|\|Escapes the next character. This allows you to match reserved characters[ ] ( ) { } . * + ? ^ $ \ |
| +|^|Matches the beginning of the input.| +|$|Matches the end of the input.| + +## 2.1 Full stop + +Full stop `.` is the simplest example of meta character. The meta character `.` +matches any single character. It will not match return or newline characters. +For example, the regular expression `.ar` means: any character, followed by the +letter `a`, followed by the letter `r`. + ++".ar" => The car parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/xc9GkU/1) + +## 2.2 Character set + +Character sets are also called character class. Square brackets are used to +specify character sets. Use a hyphen inside a character set to specify the +characters' range. The order of the character range inside square brackets +doesn't matter. For example, the regular expression `[Tt]he` means: an uppercase +`T` or lowercase `t`, followed by the letter `h`, followed by the letter `e`. + ++"[Tt]he" => The car parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/2ITLQ4/1) + +A period inside a character set, however, means a literal period. The regular +expression `ar[.]` means: a lowercase character `a`, followed by letter `r`, +followed by a period `.` character. + ++"ar[.]" => A garage is a good place to park a car. ++ +[Test the regular expression](https://regex101.com/r/wL3xtE/1) + +### 2.2.1 Negated character set + +In general, the caret symbol represents the start of the string, but when it is +typed after the opening square bracket it negates the character set. For +example, the regular expression `[^c]ar` means: any character except `c`, +followed by the character `a`, followed by the letter `r`. + ++"[^c]ar" => The car parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/nNNlq3/1) + +## 2.3 Repetitions + +Following meta characters `+`, `*` or `?` are used to specify how many times a +subpattern can occur. These meta characters act differently in different +situations. + +### 2.3.1 The Star + +The symbol `*` matches zero or more repetitions of the preceding matcher. The +regular expression `a*` means: zero or more repetitions of preceding lowercase +character `a`. But if it appears after a character set or class then it finds +the repetitions of the whole character set. For example, the regular expression +`[a-z]*` means: any number of lowercase letters in a row. + ++"[a-z]*" => The car parked in the garage #21. ++ +[Test the regular expression](https://regex101.com/r/7m8me5/1) + +The `*` symbol can be used with the meta character `.` to match any string of +characters `.*`. The `*` symbol can be used with the whitespace character `\s` +to match a string of whitespace characters. For example, the expression +`\s*cat\s*` means: zero or more spaces, followed by lowercase character `c`, +followed by lowercase character `a`, followed by lowercase character `t`, +followed by zero or more spaces. + ++"\s*cat\s*" => The fat cat sat on the concatenation. ++ +[Test the regular expression](https://regex101.com/r/gGrwuz/1) + +### 2.3.2 The Plus + +The symbol `+` matches one or more repetitions of the preceding character. For +example, the regular expression `c.+t` means: lowercase letter `c`, followed by +at least one character, followed by the lowercase character `t`. It needs to be +clarified that `t` is the last `t` in the sentence. + ++"c.+t" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/Dzf9Aa/1) + +### 2.3.3 The Question Mark + +In regular expression the meta character `?` makes the preceding character +optional. This symbol matches zero or one instance of the preceding character. +For example, the regular expression `[T]?he` means: Optional the uppercase +letter `T`, followed by the lowercase character `h`, followed by the lowercase +character `e`. + ++"[T]he" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/cIg9zm/1) + ++"[T]?he" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/kPpO2x/1) + +## 2.4 Braces + +In regular expression braces that are also called quantifiers are used to +specify the number of times that a character or a group of characters can be +repeated. For example, the regular expression `[0-9]{2,3}` means: Match at least +2 digits but not more than 3 ( characters in the range of 0 to 9). + ++"[0-9]{2,3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Test the regular expression](https://regex101.com/r/juM86s/1) + +We can leave out the second number. For example, the regular expression +`[0-9]{2,}` means: Match 2 or more digits. If we also remove the comma the +regular expression `[0-9]{3}` means: Match exactly 3 digits. + ++"[0-9]{2,}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Test the regular expression](https://regex101.com/r/Gdy4w5/1) + ++"[0-9]{3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Test the regular expression](https://regex101.com/r/Sivu30/1) + +## 2.5 Capturing Group + +A capturing group is a group of sub-patterns that is written inside Parentheses +`(...)`. Like as we discussed before that in regular expression if we put a quantifier +after a character then it will repeat the preceding character. But if we put quantifier +after a capturing group then it repeats the whole capturing group. For example, +the regular expression `(ab)*` matches zero or more repetitions of the character +"ab". We can also use the alternation `|` meta character inside capturing group. +For example, the regular expression `(c|g|p)ar` means: lowercase character `c`, +`g` or `p`, followed by character `a`, followed by character `r`. + ++"(c|g|p)ar" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/tUxrBG/1) + +Note that capturing groups do not only match but also capture the characters for use in +the parent language. The parent language could be python or javascript or virtually any +language that implements regular expressions in a function definition. + +### 2.5.1 Non-capturing group + +A non-capturing group is a capturing group that only matches the characters, but +does not capture the group. A non-capturing group is denoted by a `?` followed by a `:` +within parenthesis `(...)`. For example, the regular expression `(?:c|g|p)ar` is similar to +`(c|g|p)ar` in that it matches the same characters but will not create a capture group. + ++"(?:c|g|p)ar" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/Rm7Me8/1) + +Non-capturing groups can come in handy when used in find-and-replace functionality or +when mixed with capturing groups to keep the overview when producing any other kind of output. +See also [4. Lookaround](#4-lookaround). + +## 2.6 Alternation + +In a regular expression, the vertical bar `|` is used to define alternation. +Alternation is like an OR statement between multiple expressions. Now, you may be +thinking that character set and alternation works the same way. But the big +difference between character set and alternation is that character set works on +character level but alternation works on expression level. For example, the +regular expression `(T|t)he|car` means: either (uppercase character `T` or lowercase +`t`, followed by lowercase character `h`, followed by lowercase character `e`) OR +(lowercase character `c`, followed by lowercase character `a`, followed by +lowercase character `r`). Note that I put the parentheses for clarity, to show that either expression +in parentheses can be met and it will match. + ++"(T|t)he|car" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/fBXyX0/1) + +## 2.7 Escaping special character + +Backslash `\` is used in regular expression to escape the next character. This +allows us to specify a symbol as a matching character including reserved +characters `{ } [ ] / \ + * . $ ^ | ?`. To use a special character as a matching +character prepend `\` before it. + +For example, the regular expression `.` is used to match any character except +newline. Now to match `.` in an input string the regular expression +`(f|c|m)at\.?` means: lowercase letter `f`, `c` or `m`, followed by lowercase +character `a`, followed by lowercase letter `t`, followed by optional `.` +character. + ++"(f|c|m)at\.?" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/DOc5Nu/1) + +## 2.8 Anchors + +In regular expressions, we use anchors to check if the matching symbol is the +starting symbol or ending symbol of the input string. Anchors are of two types: +First type is Caret `^` that check if the matching character is the start +character of the input and the second type is Dollar `$` that checks if matching +character is the last character of the input string. + +### 2.8.1 Caret + +Caret `^` symbol is used to check if matching character is the first character +of the input string. If we apply the following regular expression `^a` (if a is +the starting symbol) to input string `abc` it matches `a`. But if we apply +regular expression `^b` on above input string it does not match anything. +Because in input string `abc` "b" is not the starting symbol. Let's take a look +at another regular expression `^(T|t)he` which means: uppercase character `T` or +lowercase character `t` is the start symbol of the input string, followed by +lowercase character `h`, followed by lowercase character `e`. + ++"(T|t)he" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/5ljjgB/1) + ++"^(T|t)he" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/jXrKne/1) + +### 2.8.2 Dollar + +Dollar `$` symbol is used to check if matching character is the last character +of the input string. For example, regular expression `(at\.)$` means: a +lowercase character `a`, followed by lowercase character `t`, followed by a `.` +character and the matcher must be end of the string. + ++"(at\.)" => The fat cat. sat. on the mat. ++ +[Test the regular expression](https://regex101.com/r/y4Au4D/1) + ++"(at\.)$" => The fat cat. sat. on the mat. ++ +[Test the regular expression](https://regex101.com/r/t0AkOd/1) + +## 3. Shorthand Character Sets + +Regular expression provides shorthands for the commonly used character sets, +which offer convenient shorthands for commonly used regular expressions. The +shorthand character sets are as follows: + +|Shorthand|Description| +|:----:|----| +|.|Any character except new line| +|\w|Matches alphanumeric characters: `[a-zA-Z0-9_]`| +|\W|Matches non-alphanumeric characters: `[^\w]`| +|\d|Matches digit: `[0-9]`| +|\D|Matches non-digit: `[^\d]`| +|\s|Matches whitespace character: `[\t\n\f\r\p{Z}]`| +|\S|Matches non-whitespace character: `[^\s]`| + +## 4. Lookaround + +Lookbehind and lookahead (also called lookaround) are specific types of +***non-capturing groups*** (Used to match the pattern but not included in matching +list). Lookarounds are used when we have the condition that this pattern is +preceded or followed by another certain pattern. For example, we want to get all +numbers that are preceded by `$` character from the following input string +`$4.44 and $10.88`. We will use following regular expression `(?<=\$)[0-9\.]*` +which means: get all the numbers which contain `.` character and are preceded +by `$` character. Following are the lookarounds that are used in regular +expressions: + +|Symbol|Description| +|:----:|----| +|?=|Positive Lookahead| +|?!|Negative Lookahead| +|?<=|Positive Lookbehind| +|? +"(T|t)he(?=\sfat)" => The fat cat sat on the mat. ++"(T|t)he(?!\sfat)" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/V32Npg/1) + +### 4.3 Positive Lookbehind + +Positive lookbehind is used to get all the matches that are preceded by a +specific pattern. Positive lookbehind is denoted by `(?<=...)`. For example, the +regular expression `(?<=(T|t)he\s)(fat|mat)` means: get all `fat` or `mat` words +from input string that are after the word `The` or `the`. + ++"(?<=(T|t)he\s)(fat|mat)" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/avH165/1) + +### 4.4 Negative Lookbehind + +Negative lookbehind is used to get all the matches that are not preceded by a +specific pattern. Negative lookbehind is denoted by `(? +"(?<!(T|t)he\s)(cat)" => The cat sat on cat. ++"The" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/dpQyf9/1) + ++"/The/gi" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/ahfiuh/1) + +### 5.2 Global search + +The `g` modifier is used to perform a global match (find all matches rather than +stopping after the first match). For example, the regular expression`/.(at)/g` +means: any character except new line, followed by lowercase character `a`, +followed by lowercase character `t`. Because we provided `g` flag at the end of +the regular expression now it will find all matches in the input string, not just the first one (which is the default behavior). + ++"/.(at)/" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/jnk6gM/1) + ++"/.(at)/g" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/dO1nef/1) + +### 5.3 Multiline + +The `m` modifier is used to perform a multi-line match. As we discussed earlier +anchors `(^, $)` are used to check if pattern is the beginning of the input or +end of the input string. But if we want that anchors works on each line we use +`m` flag. For example, the regular expression `/at(.)?$/gm` means: lowercase +character `a`, followed by lowercase character `t`, optionally anything except +new line. And because of `m` flag now regular expression engine matches pattern +at the end of each line in a string. + ++"/.at(.)?$/" => The fat + cat sat + on the mat. ++ +[Test the regular expression](https://regex101.com/r/hoGMkP/1) + ++"/.at(.)?$/gm" => The fat + cat sat + on the mat. ++ +[Test the regular expression](https://regex101.com/r/E88WE2/1) + +## 6. Greedy vs lazy matching +By default regex will do greedy matching , means it will match as long as +possible. we can use `?` to match in lazy way means as short as possible + ++"/(.*at)/" => The fat cat sat on the mat.+ + +[Test the regular expression](https://regex101.com/r/AyAdgJ/1) + ++"/(.*?at)/" => The fat cat sat on the mat.+ + +[Test the regular expression](https://regex101.com/r/AyAdgJ/2) + + +## Contribution + +* Open pull request with improvements +* Discuss ideas in issues +* Spread the word +* Reach out with any feedback [](https://twitter.com/ziishaned) + +## License + +MIT © [Zeeshan Ahmad](https://twitter.com/ziishaned) diff --git a/translations/README-fr.md b/translations/README-fr.md new file mode 100644 index 00000000..4bccd742 --- /dev/null +++ b/translations/README-fr.md @@ -0,0 +1,491 @@ ++
+ + + +## Traductions: + +* [English](../README.md) +* [German](../translations/README-de.md) +* [Español](../translations/README-es.md) +* [Français](../translations/README-fr.md) +* [Português do Brasil](../translations/README-pt_BR.md) +* [中文版](../translations/README-cn.md) +* [日本語](../translations/README-ja.md) +* [한국어](../translations/README-ko.md) +* [Turkish](../translations/README-tr.md) +* [Greek](../translations/README-gr.md) +* [Magyar](../translations/README-hu.md) +* [Polish](../translations/README-pl.md) +* [Русский](../translations/README-ru.md) +* [Tiếng Việt](../translations/README-vn.md) +* [فارسی](../translations/README-fa.md) +* [עברית](../translations/README-he.md) + +## Qu'est-ce qu'une expression régulière? + +[](https://gum.co/learn-regex) + +> Une expression régulière est un groupement de caractères ou symboles utilisés pour trouver un schéma spécifique dans un texte. + +Une expression régulière est un schéma qui est comparé à une chaîne de caractères (string) de gauche à droite. Le mot "Expression régulière" +est un terme entier, souvent abrégé par "regex" ou "regexp". Une expression régulière est utilisée pour remplacer un texte à l'intérieur +d'une chaîne de caractères (string), valider un formulaire, extraire une portion de chaine de caractères (string) basée sur un schéma, et bien plus encore. + +Imaginons que nous écrivons une application et que nous voulons définir des règles pour le choix d'un pseudonyme. Nous voulons autoriser +le pseudonyme à contenir des lettres, des nombres, des underscores et des traits d'union. Nous voulons aussi limiter le nombre +de caractères dans le pseudonyme pour qu'il n'ait pas l'air moche. Nous utilisons l'expression régulière suivante pour valider un pseudonyme: +
+ ++ +
+
++
+ +L'expression régulière ci-dessus peut accepter les chaines de caractères (string) `john_doe`, `jo-hn_doe` et `john12_as`. Ça ne fonctionne pas avec `Jo` car cette chaine de caractères (string) contient une lettre majuscule et elle est trop courte. + +## Table des matières + +- [Introduction](#1-introduction) +- [Meta-caractères](#2-meta-caractères) + - [Full stop](#21-full-stop) + - [Inclusion de caractères](#22-inclusion-de-caractères) + - [Exclusion de caractères](#221-exclusion-de-caractères) + - [Répétitions](#23-répétitions) + - [Astérisque](#231-Asterisque) + - [Le Plus](#232-le-plus) + - [Le Point d'Interrogation](#233-le-point-d'interrogation) + - [Accolades](#24-accolades) + - [Groupement de caractères](#25-groupement-de-caractères) + - [Alternation](#26-alternation) + - [Caractère d'échappement](#27-caractère-d'échappement) + - [Ancres](#28-ancres) + - [Circonflexe](#281-circonflexe) + - [Dollar](#282-dollar) +- [Liste de caractères abrégés](#3-liste-de-caractères-abrégés) +- [Recherche](#4-recherche) + - [Recherche avant positive](#41-recherche-avant-positive) + - [Recherche avant négative](#42-recherche-avant-négative) + - [Recherche arrière positive](#43-recherche-arrière-positive) + - [Recherche arrière négative](#44-recherche-arrière-négative) +- [Drapeaux](#5-drapeaux) + - [Insensible à la casse](#51-insensible-à-la-casse) + - [Correspondance globale](#52-recherche-globale) + - [Multilignes](#53-multilignes) + +## 1. Introduction + +Une expression régulière est un schéma de caractères utilisés pour effectuer une recherche dans un texte. +Par exemple, l'expression régulière `the` signifie : la lettre `t`, suivie de la lettre `h`, suivie de la lettre `e`. + ++
+"the" => The fat cat sat on the mat. ++ +[Essayer l'expression régulière](https://regex101.com/r/dmRygT/1) + +L'expression régulière `123` coïncide à la chaîne `123`. Chaque caractère de l'expression régulière est comparée à la chaîne passée en entrée, caractère par caractère. Les expressions régulières sont normalement sensibles à la casse, donc l'expression régulière `The` ne va pas coïncider à la chaîne de caractère `the`. + ++"The" => The fat cat sat on the mat. ++ +[Essayer l'expression régulière](https://regex101.com/r/1paXsy/1) + +## 2. Meta-caractères + +Les meta-caractères sont les blocs de construction des expressions régulières. Les meta-caractères sont interprétés de manière particulière. Certains meta-caractères ont des significations spéciales et sont écrits entre crochets. +Significations des meta-caractères: + +|Meta-caractère|Description| +|:----:|----| +|.|Un point coïncide avec n'importe quel caractère unique à part le retour à la ligne.| +|[ ]|Classe de caractères. Coïncide avec n'importe quel caractère entre crochets.| +|[^ ]|Négation de classe de caractère. Coïncide avec n'importe quel caractère qui n'est pas entre les crochets.| +|*|Coïncide avec 0 ou plus répétitions du caractère précédent.| +|+|Coïncide avec 1 ou plus répétitions du caractère précédent.| +|?|Rend le caractère précédent optionnel.| +|{n,m}|Accolades. Coïncide avec au moins "n" mais pas plus que "m" répétition(s) du caractère précédent.| +|(xyz)|Groupe de caractères. Coïncide avec les caractères "xyz" dans l'ordre exact.| +|||Alternation (ou). Coïncide soit avec le caractère avant ou après le symbole.| +|\|Échappe le prochain caractère. Cela permet de faire coïncider des caractères réservés tels que[ ] ( ) { } . * + ? ^ $ \ |
| +|^|Coïncide avec le début de la chaîne de caractères (string).| +|$|Coïncide avec la fin de la chaîne de caractères (string).| + +## 2.1 Full stop + +Le full stop `.` est l'exemple le plus simple d'un meta-caratère. Le `.` coïncide avec n'importe quel caractère unique, mais ne coïncide pas avec les caractères de retour ou de nouvelle ligne. Par exemple, l'expression régulière `.ar` signifie : n'importe quel caractère suivi par la lettre `a`, suivie par la lettre `r`. + ++".ar" => The car parked in the garage. ++ +[Essayer l'expression régulière](https://regex101.com/r/xc9GkU/1) + +## 2.2 Inclusions de caractères + +Les inclusions de caractères sont également appelées classes de caractères. Les crochets sont utilisés pour spécifier les inclusions de caractères. Un trait d'union utilisé dans une inclusion de caractères permet de définir une gamme de caractères. L'ordre utilisé dans la gamme de caractère n'a pas d'importance. Par exemple, l'expression régulière `[Tt]he` signifie : un `T` majuscule ou `t` minuscule, suivie par la lettre `h`, suivie par la lettre `e`. + ++"[Tt]he" => The car parked in the garage. ++ +[Essayer l'expression régulière](https://regex101.com/r/2ITLQ4/1) + +L'utilisation du point dans une inclusion de caractère signifie toutefois un `.` littéral. L'expression régulière `ar[.]` signifie : un `a` minuscule, suivi par la lettre `r` minuscule, suivie par un `.` (point). + ++"ar[.]" => A garage is a good place to park a car. ++ +[Essayer l'expression régulière](https://regex101.com/r/wL3xtE/1) + +### 2.2.1 Exclusion de caractères + +En règle générale, le caractère circonflexe représente le début d'une chaîne de caractères (string). Néanmoins, lorsqu'il est utilisé après le crochet ouvrant, il permet d'exclure la gamme de caractères. Par exemple, l'expression régulière `[^c]ar` signifie : n'importe quel caractère sauf `c`, suivi par la lettre `a`, suivie par la lettre `r`. + ++"[^c]ar" => The car parked in the garage. ++ +[Essayer l'expression régulière](https://regex101.com/r/nNNlq3/1) + +## 2.3 Répétitions + +Les meta-caractères suivants `+`, `*` ou `?` sont utilisés pour spécifier combien de fois un sous-schéma peut apparaître. Ces meta-caractères agissent différemment selon la situation dans laquelle ils sont utilisés. + +### 2.3.1 Astérisque + +Le symbole `*` correspond à zéro ou plus de répétitions du schéma précédent. L'expression régulière `a*` signifie : zéro ou plus de répétitions +du précédent `a` minuscule. Mais si il se trouve après une liste de caractères alors il s'agit de la répétition de la liste entière. +Par exemple, l'expression régulière `[a-z]*` signifie : peu importe la chaine tant qu'il s'agit de lettres minuscules. + ++"[a-z]*" => The car parked in the garage #21. ++ +[Essayer l'expression régulière](https://regex101.com/r/7m8me5/1) + +Le symbole `*` peut être utilisé avec le meta-caractère `.` pour correspondre à n'importe quelle chaîne de caractères (string) `.*`. Le symbole `*` peut être utilisé avec le +caractère espace vide `\s` pour correspondre à une chaîne d'espaces vides. Par exemple, l'expression `\s*cat\s*` signifie : zéro ou plus +d'espaces, suivis du caractère `c` minuscule, suivi par le caractère `a` minuscule, suivi par le caractère `t` minuscule, suivi par +zéro ou plus d'espaces. + ++"\s*cat\s*" => The fat cat sat on the concatenation. ++ +[Essayer l'expression régulière](https://regex101.com/r/gGrwuz/1) + +### 2.3.2 Le Plus + +Le meta-caractère `+` correspond à une ou plusieurs répétitions du caractère précédent. Par exemple, l'expression régulière `c.+t` signifie : la lettre `c` minuscule, suivie par au moins un caractère, suivie par la lettre `t` minuscule. Le `t` coïncide par conséquent avec le dernier `t` de la phrase. + ++"c.+t" => The fat cat sat on the mat. ++ +[Essayer l'expression régulière](https://regex101.com/r/Dzf9Aa/1) + +### 2.3.3 Le point d'interrogation + +Le meta-caractère `?` rend le caractère précédent optionnel. Ce symbole permet de faire coïncider 0 ou une instance du caractère précédent. Par exemple, l'expression régulière `[T]?he` signifie : la lettre `T` majuscule optionnelle, suivie par la lettre `h` minuscule, suivie par la lettre `e` minuscule. + ++"[T]he" => The car is parked in the garage. ++ +[Essayer l'expression régulière](https://regex101.com/r/cIg9zm/1) + ++"[T]?he" => The car is parked in the garage. ++ +[Essayer l'expression régulière](https://regex101.com/r/kPpO2x/1) + +## 2.4 Accolades + +Dans une expression régulière, les accolades, qui sont aussi appelées quantifieurs, sont utilisées pour spécifier le nombre de fois qu'un +caractère ou un groupe de caractères peut être répété. Par exemple, l'expression régulière `[0-9]{2,3}` signifie : trouve au moins 2 chiffres mais pas plus de 3 +(caractères dans la gamme de 0 à 9). + ++"[0-9]{2,3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Essayer l'expression régulière](https://regex101.com/r/juM86s/1) + +Nous pouvons omettre le second nombre. Par exemple, l'expression régulière `[0-9]{2,}` signifie : trouve 2 chiffres ou plus. Si nous supprimons aussi +la virgule l'expression régulière `[0-9]{3}` signifie : trouve exactement 3 chiffres. + ++"[0-9]{2,}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Essayer l'expression régulière](https://regex101.com/r/Gdy4w5/1) + ++"[0-9]{3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Essayer l'expression régulière](https://regex101.com/r/Sivu30/1) + +## 2.5 Groupement de caractères + +Un groupement de caractères est un groupe de sous-schémas qui sont écrits entre parenthèses `(...)`. Nous avions mentionné plus tôt que, dans une expression régulière, +si nous mettons un quantifieur après un caractère alors le caractère précédent sera répété. Mais si nous mettons un quantifieur après un groupement de caractères alors +il répète le groupement de caractères en entier. Par exemple, l'expression régulière `(ab)*` trouve zéro ou plus de répétitions des caractères "ab". +Nous pouvons aussi utiliser le meta-caractère d'alternation `|` à l'intérieur d'un groupement. Par exemple, l'expression régulière `(c|g|p)ar` signifie : caractère `c` minuscule, +`g` ou `p`, suivi par le caractère `a`, suivi par le caractère `r`. + ++"(c|g|p)ar" => The car is parked in the garage. ++ +[Essayer l'expression régulière](https://regex101.com/r/tUxrBG/1) + +## 2.6 Alternation + +Dans une expression régulière, la barre verticale `|` est utilisée pour définir une alternation. L'alternation est comme une condition entre plusieurs expressions. Maintenant, +nous pourrions penser que la liste de caractères et l'alternation sont la même chose. Mais la grande différence entre une liste de caractères et l'alternation +est que la liste de caractères fonctionne au niveau des caractères mais l'alternation fonctionne au niveau de l'expression. Par exemple, l'expression régulière +`(T|t)he|car` signifie : le caractère `T` majuscule ou `t` minuscule, suivi par le caractère `h` minuscule, suivi par le caractère `e` minuscule +ou le caractère `c` minuscule, suivi par le caractère `a` minuscule, suivit par le caractère `r` minuscule. + ++"(T|t)he|car" => The car is parked in the garage. ++ +[Essayer l'expression régulière](https://regex101.com/r/fBXyX0/1) + +## 2.7 Caractère d'échappement + +L'antislash `\` est utilisé dans les expressions régulières pour échapper (ignorer) le caractère suivant. Cela permet de spécifier un symbole comme caractère à trouver +y compris les caractères réservés `{ } [ ] / \ + * . $ ^ | ?`. Pour utiliser un caractère spécial comme caractère à trouver, préfixer `\` avant celui-ci. +Par exemple, l'expression régulière `.` est utilisée pour trouver n'importe quel caractère sauf le retour de ligne. Donc pour trouver `.` dans une chaine de caractères (string) +l'expression régulière `(f|c|m)at\.?` signifie : la lettre minuscule `f`, `c` ou `m`, suivie par le caractère `a` minuscule, suivi par la lettre +`t` minuscule, suivie par le caractère optionnel `.`. + ++"(f|c|m)at\.?" => The fat cat sat on the mat. ++ +[Essayer l'expression régulière](https://regex101.com/r/DOc5Nu/1) + +## 2.8 Ancres + +Dans les expressions régulières, nous utilisons des ancres pour vérifier si le symbole trouvé est le premier ou dernier symbole de la +chaine de caractères (string). Il y a 2 types d'ancres : Le premier type est le circonflexe `^` qui cherche si le caractère est le premier +caractère de la chaine de caractères (string) et le deuxième type est le Dollar `$` qui vérifie si le caractère est le dernier caractère de la chaine de caractères (string). + +### 2.8.1 Circonflexe + +Le symbole circonflexe `^` est utilisé pour vérifier si un caractère est le premier caractère de la chaine de caractères (string). Si nous appliquons l'expression régulière +suivante `^a` (si a est le premier symbole) à la chaine de caractères (string) `abc`, ça coïncide. Mais si nous appliquons l'expression régulière `^b` sur cette même chaine de caractères (string), +ça ne coïncide pas. Parce que dans la chaine de caractères (string) `abc` "b" n'est pas le premier symbole. Regardons une autre expression régulière +`^(T|t)he` qui signifie : le caractère `T` majuscule ou le caractère `t` minuscule est le premier symbole de la chaine de caractères (string), +suivi par le caractère `h` minuscule, suivi par le caractère `e` minuscule. + ++"(T|t)he" => The car is parked in the garage. ++ +[Essayer l'expression régulière](https://regex101.com/r/5ljjgB/1) + ++"^(T|t)he" => The car is parked in the garage. ++ +[Essayer l'expression régulière](https://regex101.com/r/jXrKne/1) + +### 2.8.2 Dollar + +Le symbole Dollar `$` est utilisé pour vérifier si un caractère est le dernier caractère d'une chaine de caractères (string). Par exemple, l'expression régulière +`(at\.)$` signifie : un caractère `a` minuscule, suivi par un caractère `t` minuscule, suivi par un caractère `.` et tout cela doit être +à la fin de la chaine de caractères (string). + ++"(at\.)" => The fat cat. sat. on the mat. ++ +[Essayer l'expression régulière](https://regex101.com/r/y4Au4D/1) + ++"(at\.)$" => The fat cat. sat. on the mat. ++ +[Essayer l'expression régulière](https://regex101.com/r/t0AkOd/1) + +## 3. Liste de caractères abrégés + +Les expressions régulières fournissent des abréviations pour les listes de caractères, ce qui offres des raccourcis pratiques pour +les expressions régulières souvent utilisées. Ces abréviations sont les suivantes : + +|Abréviation|Description| +|:----:|----| +|.|N'importe quel caractère à part le retour de ligne| +|\w|Caractères alphanumériques : `[a-zA-Z0-9_]`| +|\W|Caractères non-alphanumériques : `[^\w]`| +|\d|Chiffres : `[0-9]`| +|\D|Non-numériques : `[^\d]`| +|\s|Espace vide : `[\t\n\f\r\p{Z}]`| +|\S|Tout sauf espace vide : `[^\s]`| + +## 4. Recherche + +La recherche en avant et en arrière sont un type spécifique appelé ***groupe non-capturant*** (utilisés pour trouver un schéma mais pas +pour l'inclure dans la liste de correspondance). Les recherches positives sont utilisées quand nous avons la condition qu'un schéma doit être précédé ou suivi +par un autre schéma. Par exemple, nous voulons tous les chiffres qui sont précédés par le caractère `$` dans la chaine de caractères suivante `$4.44 and $10.88`. +Nous allons utiliser l'expression régulière suivante `(?<=\$)[0-9\.]*` qui signifie : trouver tous les nombres qui contiennent le caractère `.` et sont précédés +par le caractère `$`. Les recherches que nous trouvons dans les expressions régulières sont les suivantes: + +|Symbole|Description| +|:----:|----| +|?=|Recherche en avant positive| +|?!|Recherche en avant négative| +|?<=|Recherche en arrière positive| +|? +"[T|t]he(?=\sfat)" => The fat cat sat on the mat. ++"[T|t]he(?!\sfat)" => The fat cat sat on the mat. ++ +[Essayer l'expression régulière](https://regex101.com/r/V32Npg/1) + +### 4.3 Recherche en arrière positive + +La recherche en arrière positive est utilisée pour trouver une chaine de caractères (string) précédée d'un schéma. La recherche en arrière positive se note +`(?<=...)`. Par exemple, l'expression régulière `(?<=[T|t]he\s)(fat|mat)` signifie : trouve tous les mots `fat` ou `mat` de la chaine de caractères (string) qui +se trouve après le mot `The` ou `the`. + ++"(?<=[T|t]he\s)(fat|mat)" => The fat cat sat on the mat. ++ +[Essayer l'expression régulière](https://regex101.com/r/avH165/1) + +### 4.4 Recherche en arrière négative + +La recherche en arrière négative est utilisée pour trouver une chaine de caractères (string) qui n'est pas précédée d'un schéma. La recherche en arrière négative se note +`(? +"(?<![T|t]he\s)(cat)" => The cat sat on cat. ++"The" => The fat cat sat on the mat. ++ +[Essayer l'expression régulière](https://regex101.com/r/dpQyf9/1) + ++"/The/gi" => The fat cat sat on the mat. ++ +[Essayer l'expression régulière](https://regex101.com/r/ahfiuh/1) + +### 5.2 Correspondance globale + +Le modifieur `g` est utilisé pour faire une recherche globale (trouver toutes les chaines de caractères (string) plutôt que de s'arrêter à la première correspondance ). Par exemple, +l'expression régulière `/.(at)/g` signifie : n'importe quel caractère sauf le retour de ligne, suivi par le caractère `a` minuscule, suivi par le caractère +`t` minuscule. Grâce au drapeau `g` à la fin de l'expression régulière maintenant il trouvera toutes les correspondances de toute la chaine de caractères (string). + ++"/.(at)/" => The fat cat sat on the mat. ++ +[Essayer l'expression régulière](https://regex101.com/r/jnk6gM/1) + ++"/.(at)/g" => The fat cat sat on the mat. ++ +[Essayer l'expression régulière](https://regex101.com/r/dO1nef/1) + +### 5.3 Multilignes + +Le modifieur `m` est utilisé pour trouver une correspondance multiligne. Comme mentionné plus tôt, les ancres `(^, $)` sont utilisés pour vérifier si le schéma +se trouve au début ou à la fin de la chaine de caractères (string). Mais si nous voulons que l'ancre soit sur chaque ligne nous utilisons le drapeau `m`. Par exemple, l'expression régulière +`/at(.)?$/gm` signifie : le caractère `a` minuscule, suivi par le caractère `t` minuscule, suivi par optionnellement n'importe quel caractère à part le retour de ligne. +Grâce au drapeau `m` maintenant le moteur d'expression régulière trouve le schéma à chaque début de ligne dans la chaine de caractères (string). + ++"/.at(.)?$/" => The fat + cat sat + on the mat. ++ +[Essayer l'expression régulière](https://regex101.com/r/hoGMkP/1) + ++"/.at(.)?$/gm" => The fat + cat sat + on the mat. ++ +[Essayer l'expression régulière](https://regex101.com/r/E88WE2/1) + +## Contribution + +* Signaler les problèmes (issues) +* Ouvrir des "pull requests" pour les améliorations +* Parlez-en autour de vous ! +* Contactez moi en anglais à ziishaned@gmail.com ou [](https://twitter.com/ziishaned) + +## License + +MIT © [Zeeshan Ahmad](https://twitter.com/ziishaned) diff --git a/translations/README-gr.md b/translations/README-gr.md new file mode 100644 index 00000000..31b1ee64 --- /dev/null +++ b/translations/README-gr.md @@ -0,0 +1,573 @@ ++
+ + + +## Μεταφράσεις: + +* [English](../README.md) +* [German](../translations/README-de.md) +* [Español](../translations/README-es.md) +* [Français](../translations/README-fr.md) +* [Português do Brasil](../translations/README-pt_BR.md) +* [中文版](../translations/README-cn.md) +* [日本語](../translations/README-ja.md) +* [한국어](../translations/README-ko.md) +* [Turkish](../translations/README-tr.md) +* [Greek](../translations/README-gr.md) +* [Magyar](../translations/README-hu.md) +* [Polish](../translations/README-pl.md) +* [Русский](../translations/README-ru.md) +* [Tiếng Việt](../translations/README-vn.md) +* [فارسی](../translations/README-fa.md) +* [עברית](../translations/README-he.md) + +## Τι είναι μια Κανονική Έκφραση (Regular Expression); + +[](https://gum.co/learn-regex) + +> Μια κανονική έκφραση είναι μια ομάδα χαρακτήρων ή συμβόλων που χρησιμοποιούνται για την εύρεση ενός συγκεκριμένου μοτίβου χαρακτήρων μέσα σ'ένα κείμενο. + +Μια κανονική έκφραση, είναι μια σειρά χαρακτήρων τους οποίους αναζητούμε μέσα σε ένα κείμενο. Η αναζήτηση αυτή +ξεκινά από τα αριστερά και συνεχίζει προς τα δεξιά. Ο όρος "Κανονική Έκφραση" είναι κάπως μεγάλος οπότε πολύ συχνά +θα τον συναντήσετε στην συντομότερη μορφή του ως "regex" ή "regexp". Οι εκφράσεις αυτές χρησιμοποιούνται +για αντικατάσταση λέξεων μέσα σε κείμενο, για επικυρώσεις τύπων, για αποκοπή ενός κομματιού +string με βάση κάποιου μοτίβου αναζήτησης και για πολλά άλλα. + +Φανταστείτε ότι πρέπει να γράψουμε μια εφαρμογή και ότι θέλουμε να ορίσουμε κανόνες για την δημιουργία +ονόματος χρήστη (username). Σ'αυτή την περίπτωση, θέλουμε να επιτρέψουμε την χρήση γραμμάτων και +αριθμών καθώς και την παύλα και κάτω παύλα. Θέλουμε επίσης να περιορίσουμε τον αριθμό χαρακτήρων +του ονόματος χρήστη ώστε να μην φαίνεται μεγάλο και άσχημο. Για να το κάνουμε αυτό, μπορούμε να χρησιμοποιήσουμε +την παρακάτω κανονική έκφραση: + +
+ ++ +
+
++
+ +Η παραπάνω κανονική έκφραση θα δεχτεί ως σωστά τα ονόματα χρήστη `john_doe`, `jo-hn_doe` και +`john12_as`. Όμως δεν θα δεχτεί το `Jo` αφού περιέχει ένα κεφαλαίο γράμμα και είναι πολύ +μικρό. + +## Πίνακας Περιεχομένων + +- [Βασικά Μοτίβα Αναζήτησης](#1-Βασικά-Μοτίβα-Αναζήτησης) +- [Μεταχαρακτήρες](#2-Μεταχαρακτήρες) + - [Τελεία](#21-Τελεία) + - [Σύνολα Χαρακτήρων](#22-Σύνολα-Χαρακτήρων) + - [Σύνολο Χαρακτήρων προς Εξαίρεση](#221-Σύνολο-Χαρακτήρων-προς-Εξαίρεση) + - [Επαναλήψεις](#23-Επαναλήψεις) + - [Ο Αστερίσκος](#231-Ο-Αστερίσκος) + - [Το Σύμβολο της Πρόσθεσης](#232-Το-Σύμβολο-της-Πρόσθεσης) + - [Το Ερωτηματικό](#233-Το-Ερωτηματικό) + - [Αγκύλες](#24-Αγκύλες) + - [Ομάδα Χαρακτήρων](#25-Ομάδα-Χαρακτήρων) + - [Εναλλαγή](#26-Εναλλαγή) + - [Ειδικός Χαρακτήρας Διαφυγής](#27-Ειδικός-Χαρακτήρας-Διαφυγής) + - [Σύμβολα "Άγκυρες"](#28-Σύμβολα-"Άγκυρες") + - [Το Σύμβολο ^](#281-Το-Σύμβολο-^) + - [Το Δολάριο](#282-Το-Δολάριο) +- [Συντομογραφίες Συνόλων Χαρακτήρων](#3-Συντομογραφίες-Συνόλων-Χαρακτήρων) +- [Αναζήτηση](#4-Αναζήτηση) + - [Θετική Αναζήτηση προς τα Μπροστά](#41-Θετική-Αναζήτηση-προς-τα-Μπροστά) + - [Αρνητική Αναζήτηση προς τα Μπροστά](#42-Αρνητική-Αναζήτηση-προς-τα-Μπροστά) + - [Θετική Αναζήτηση προς τα Πίσω](#43-Θετική-Αναζήτηση-προς-τα-Πίσω) + - [Αρνητική Αναζήτηση προς τα Πίσω](#44-Αρνητική-Αναζήτηση-προς-τα-Πίσω) +- [Σημαίες](#5-Σημαίες) + - [Χωρίς Διάκριση Πεζών-Κεφαλαίων](#51-Χωρίς-Διάκριση-Πεζών-Κεφαλαίων) + - [Καθολική Αναζήτηση](#52-Καθολική-Αναζήτηση) + - [Πολλές Γραμμές](#53-Πολλές-Γραμμές) + +## 1. Βασικά Μοτίβα Αναζήτησης + +Μια κανονική έκφραση είναι απλώς ένα μοτίβο, δηλαδή μια σειρά χαρακτήρων, που χρησιμοποιούμε ώστε να κάνουμε +αναζήτηση σε ένα κείμενο (πχ για να βρούμε ένα γράμμα ή μια λέξη κλπ). Για παράδειγμα, η κανονική έκφραση `the` +αναπαριστά: το γράμμα `t`, ακολουθούμενο από το γράμμα `h`, ακολουθούμενο από το γράμμα `e`. + ++
+"the" => The fat cat sat on the mat. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/dmRygT/1) + +Η κανονική έκφραση `123` "ταιριάζει" με το string `123`. Η έκφραση αυτή +αναζητείται μέσα σ'ένα string εισόδου αντιστοιχίζοντας κάθε χαρακτήρα της με κάθε +χαρακτήρα του string. Οι κανονικές εκφράσεις συνήθως λαμβάνουν υπόψη το αν τα γράμματα είναι +κεφαλαία ή πεζά και άρα η έκφραση `The` δεν θα ταίριαζε με το string `the`. + ++"The" => The fat cat sat on the mat. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/1paXsy/1) + +## 2. Μεταχαρακτήρες + +Οι μεταχαρακτήρες είναι τα δομικά στοιχεία των κανονικών εκφράσεων. Δεν αντιπροσωπεύουν +τον εαυτό τους αλλά ερμηνεύονται με ειδικό τρόπο. Μερικοί από αυτούς, έχουν +ειδικό νόημα και γι'αυτό γράφονται μέσα σε αγκύλες. Οι μεταχαρακτήρες είναι οι παρακάτω: + +|Μεταχαρακτήρας|Περιγραφή| +|:----:|----| +|.|Η τελεία είναι ισοδύναμη με οποιονδήποτε μεμονωμένο χαρακτήρα εκτός από αυτόν για αλλαγή γραμμής.| +|[ ]|Κλάση χαρακτήρων. Είναι ισοδύναμη με οποιονδήποτε χαρακτήρα βρίσκεται μέσα σε αγκύλες.| +|[^ ]|Κλάση χαρακτήρων εξαίρεσης. Είναι ισοδύναμη με οποιονδήποτε χαρακτήρα δεν βρίσκεται μέσα σε αγκύλες| +|*|Ταιριάζει με 0 ή παραπάνω επαναλήψεις του προηγούμενου συμβόλου.| +|+|Ταιριάζει με 1 ή παραπάνω επαναλήψεις του προηγούμενου συμβόλου.| +|?|Κάνει το προηγούμενο σύμβολο προαιρετικό.| +|{n,m}|Αγκύλες. Ταιριάζει με τουλάχιστον "n" αλλά όχι με παραπάνω από "m" επαναλήψεις του προηγούμενου συμβόλου.| +|(xyz)|Ομάδα χαρακτήρων. Είναι ισοδύναμη με τους χαρακτήρες xyz ακριβώς με την σειρά στην οποία βρίσκονται.| +|||Εναλλαγή. Ταιριάζει είτε με τους χαρακτήρες που βρίσκονται πριν είτε μετά το σύμβολο.| +|\|Παραλείπει το ειδικό νόημα του χαρακτήρα. Αυτό μας επιτρέπει να ταιριάξουμε χαρακτήρες +ειδικής χρήσης[ ] ( ) { } . * + ? ^ $ \ |
| +|^|Αναζητά το μοτίβο που ακολουθεί στην αρχή μιας εισόδου.| +|$|Αναζητά το μοτίβο που ακολουθεί στο τέλος μιας εισόδου.| + +## 2.1 Τελεία + +Η τελεία `.` είναι το πιο απλό παράδειγμα μεταχαρακτήρα. Είναι ισοδύναμη με οποιονδήποτε +μεμονωμένο χαρακτήρα με εξαίρεση τον χαρακτήρα για επιστροφή στην αρχή της γραμμής +και αυτόν για νέα σειρά. Για παράδειγμα, η κανονική έκφραση `.ar` αναπαριστά: οποιονδήποτε +χαρακτήρα που ακολουθείται από το γράμμα `a`, που με την σειρά του ακολουθείται από το γράμμα `r`. + ++".ar" => The car parked in the garage. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/xc9GkU/1) + +## 2.2 Σύνολα Χαρακτήρων + +Τα σύνολα χαρακτήρων καλούνται αλλιώς και κλάσεις χαρακτήρων. Τα σύνολα αυτά γράφονται μέσα +σε αγκύλες. Για τον ορισμό της εμβέλειας ενός τέτοιου συνόλου χρησιμοποιείται μια παύλα +για να διαχωρίζει την αρχή από το τέλος. Η σειρά των χαρακτήρων, που βρίσκονται μέσα στην +εμβέλεια του συνόλου που ορίζεται από τις αγκύλες, δεν έχει σημασία. Για παράδειγμα, +η κανονική έκφραση `[Tt]he` αναπαριστά: ένα κεφαλαίο `T` ή ένα πεζό `t`, που ακολουθείται +από το γράμμα `h`, που με τη σειρά του ακολουθείται από το γράμμα `e`. + ++"[Tt]he" => The car parked in the garage. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/2ITLQ4/1) + +Όμως, μια τελεία μέσα σε ένα σύνολο χαρακτήρων, είναι μια κλασική τελεία και δεν εκλαμβάνεται +ως μεταχαρακτήρας. Η κανονική έκφραση `ar[.]` αναπαριστά: ένα πεζό γράμμα `a`, που +ακολουθείται από το γράμμα `r`, που με την σειρά του ακολουθείται από τον χαρακτήρα `.`. + ++"ar[.]" => A garage is a good place to park a car. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/wL3xtE/1) + +### 2.2.1 Σύνολο Χαρακτήρων προς Εξαίρεση + +Γενικά, το σύμβολο ^ αναπαριστά την αρχή ενός string, αλλά όταν βρίσκεται +μέσα σε αγκύλες ([] όχι {}), αναπαριστά ένα σύνολο χαρακτήρων που θα εξαιρεθούν από την διαδικασία +της αναζήτησης. Για παράδειγμα, η κανονική έκφραση `[^c]ar` αναπαριστά: οποιονδήποτε χαρακτήρα +εκτός από το `c`, που ακολουθείται από τον χαρακτήρα `a`, που ακολουθείται από +το `r`. + ++"[^c]ar" => The car parked in the garage. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/nNNlq3/1) + +## 2.3 Επαναλήψεις + +Οι μεταχαρακτήρες `+`, `*` και `?`, χρησιμοποιούνται για να προσδιοριστεί +το πόσες φορές επαναλαμβάνεται ένα υπό-μοτίβο χαρακτήρων μέσα στο string εισόδου. Αυτοί οι +μεταχαρακτήρες συμπεριφέρονται διαφορετικά ανάλογα με την περίσταση. + +### 2.3.1 Ο Αστερίσκος + +Το σύμβολο `*` ψάχνει για μηδέν ή παραπάνω επαναλήψεις της έκφρασης +που βρίσκεται πριν από αυτό. Η κανονική έκφραση `a*` αναπαριστά: αναζήτηση για μηδέν ή παραπάνω +επαναλήψεις του πεζού χαρακτήρα `a`. Όταν το σύμβολο * βρίσκεται μετά από ένα σύνολο +ή κλάση χαρακτήρων, τότε εντοπίζει ολόκληρο το σύνολο όσες φορές και αν υπάρχει σε μια +γραμμή. Για παράδειγμα, η κανονική έκφραση `[a-z]*` αναπαριστά: οποιονδήποτε συνδυασμό +πεζών γραμμάτων που βρίσκονται στην σειρά. + ++"[a-z]*" => The car parked in the garage #21. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/7m8me5/1) + +Το σύμβολο `*` μπορεί να χρησιμοποιηθεί σε συνδυασμό με τον χαρακτήρα `.` ώστε +να αναζητηθεί μια ακολουθία χαρακτήρων. Μπορεί επίσης να χρησιμοποιηθεί με τον +χαρακτήρα κενού `\s` ώστε να αναζητηθεί μια ακολουθία κενών. Για παράδειγμα, η +έκφραση `\s*cat\s*` αναπαριστά: μηδέν ή περισσότερα κενά, που ακολουθούνται από +τον πεζό χαρακτήρα `c`, που ακολουθείται από τον πεζό χαρακτήρα `a`, που ακολουθείται + από τον πεζό χαρακτήρα `t`, που ακολουθείται από μηδέν ή περισσότερα κενά. + ++"\s*cat\s*" => The fat cat sat on the concatenation. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/gGrwuz/1) + +### 2.3.2 Το Σύμβολο της Πρόσθεσης + +Με σύμβολο `+` γίνεται αναζήτηση για μία ή περισσότερες επαναλήψεις του προηγούμενου του χαρακτήρα. +Για παράδειγμα, η κανονική έκφραση `c.+t` αναπαριστά: το πεζό γράμμα `c`, που ακολουθείται +από τουλάχιστον ένα χαρακτήρα, που ακολουθείται από το πεζό γράμμα `t`. Πρέπει να διευκρινίσουμε +ότι το `t` είναι το τελευταίο `t` της πρότασης. + ++"c.+t" => The fat cat sat on the mat. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/Dzf9Aa/1) + +### 2.3.3 Το Ερωτηματικό + +Σε μια κανονική έκφραση, ο μεταχαρακτήρας `?` κάνει τον χαρακτήρα που βρίσκεται πριν από αυτόν, +προαιρετικό ως προς την εύρεσή του. Έτσι γίνεται αναζήτηση για μηδέν ή παραπάνω περιπτώσεις εμφάνισης +του προηγούμενου από το ερωτηματικό χαρακτήρα. Για παράδειγμα, η κανονική έκφραση `[T]?he` αναπαριστά: +το προαιρετικό κεφαλαίο `T`, που ακολουθείται από πεζό `h`, που ακολουθείται από +πεζό `e`. + ++"[T]he" => The car is parked in the garage. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/cIg9zm/1) + ++"[T]?he" => The car is parked in the garage. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/kPpO2x/1) + +## 2.4 Αγκύλες + +Οι αγκύλες στις κανονικές εκφράσεις ονομάζονται αλλιώς και "ποσοτικοποιητές" αφού +χρησιμοποιούνται για την εύρεση όλων επαναλήψεων ενός χαρακτήρα ή μιας +ομάδας χαρακτήρων μέσα σ'ένα κείμενο. Για παράδειγμα, η κανονική έκφραση `[0-9]{2,3}` αναπαριστά: την +αναζήτηση τουλάχιστον 2 ψηφίων το ένα μετά το άλλο αλλά όχι παραπάνω από 3 (στους χαρακτήρες από το 0 ως το 9). + ++"[0-9]{2,3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/juM86s/1) + +Μπορούμε να παραλείψουμε τον δεύτερο αριθμό. Για παράδειγμα, η κανονική έκφραση +`[0-9]{2,}` αναπαριστά: την αναζήτηση 2 ή περισσότερων ψηφίων το ένα μετά το άλλο. Αν αφαιρέσουμε και +την κόμμα, τότε η κανονική έκφραση `[0-9]{3}` αναπαριστά: την σύγκριση ακριβώς 3 ψηφίων. + ++"[0-9]{2,}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/Gdy4w5/1) + ++"[0-9]{3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/Sivu30/1) + +## 2.5 Ομάδα Χαρακτήρων + +Μια ομάδα χαρακτήρων είναι μια ομάδα υπό-μοτίβων που γράφονται μέσα σε παρενθέσεις `(...)`. +Όπως είπαμε και προηγουμένως, σε μια κανονική έκφραση, αν τοποθετήσουμε έναν ποσοτικοποιητή μετά από έναν +χαρακτήρα, τότε αυτός ο χαρακτήρας θα βρεθεί όσες φορές και αν υπάρχει μέσα στο κείμενο στο οποίο +εκτελείται η αναζήτηση. Παρομοίως, αν τον βάλουμε μετά από μια ομάδα χαρακτήρων. Για παράδειγμα, +η κανονική έκφραση `(ab)*` ταιριάζει με μηδέν ή παραπάνω επαναλήψεις του χαρακτήρα +"ab". Ακόμη, μπορούμε να χρησιμοποιήσουμε τον μεταχαρακτήρα εναλλαγής `|` μέσα σε μια ομάδα χαρακτήρων. +Για παράδειγμα, η κανονική έκφραση `(c|g|p)ar` αναπαριστά: τους πεζούς χαρακτήρες `c`, +`g` ή `p`, που ακολουθούνται από τον χαρακτήρα `a`, που ακολουθείται από τον χαρακτήρα `r`. + ++"(c|g|p)ar" => The car is parked in the garage. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/tUxrBG/1) + +## 2.6 Εναλλαγή + +Στις κανονικές εκφράσεις, η κάθετη γραμμή `|`, ορίζει μια εναλλαγή. +Έτσι δηλαδή γίνεται μια επιλογή μεταξύ πολλαπλών εκφράσεων. Ίσως σκέφτεστε ότι +η εναλλαγή και τα σύνολα , λειτουργούν με τον ίδιο τρόπο. Αλλά η μεγάλη διαφορά τους +είναι ότι τα σύνολα χαρακτήρων δουλεύουν με χαρακτήρες ενώ η εναλλαγή με εκφράσεις. +Για παράδειγμα, η κανονική έκφραση `(T|t)he|car` αναπαριστά: τον κεφαλαίο χαρακτήρα `T` +ή τον πεζό χαρακτήρα `t`, που ακολουθείται από πεζό χαρακτήρα `h`, που ακολουθείται από +πεζό χαρακτήρα `e` ή πεζό χαρακτήρα `c`, που ακολουθείται από πεζό χαρακτήρα `a`, που +ακολουθείται από πεζό χαρακτήρα `r`. + ++"(T|t)he|car" => The car is parked in the garage. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/fBXyX0/1) + +## 2.7 Ειδικός Χαρακτήρας Διαφυγής + +Το σύμβολο `\` χρησιμοποιείται στις κανονικές εκφράσεις ώστε να αγνοηθεί η ειδική σημασία +που μπορεί να έχει ο χαρακτήρας που βρίσκεται μετά από αυτό. Αυτό μας επιτρέπει να αναζητήσουμε ένα +σύμβολο, συμπεριλαμβανομένων των ειδικών χαρακτήρων `{ } [ ] / \ + * . $ ^ | ?`. Άρα για αναζήτηση +ειδικών χαρακτήρων, τοποθετούμε ακριβώς πριν το σύμβολο `\`. + +Για παράδειγμα, η κανονική έκφραση `.` χρησιμοποιείται για αναζήτηση οποιουδήποτε χαρακτήρα εκτός από +αυτόν για την νέα γραμμή. Η παρακάτω κανονική έκφραση ψάχνει για το σύμβολο της τελείας `.` σε ένα string εισόδου. Η +`(f|c|m)at\.?` αναπαριστά: ένα πεζό γράμμα `f`, `c` ή `m`, που ακολουθείται από τον πεζό τον +χαρακτήρα `a`, που ακολουθείται από το πεζό γράμμα `t`, που ακολουθείται από τον προαιρετικό χαρακτήρα `.`. + ++"(f|c|m)at\.?" => The fat cat sat on the mat. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/DOc5Nu/1) + +## 2.8 Σύμβολα "Άγκυρες" + +Σε μια κανονική έκφραση, χρησιμοποιούμε "άγκυρες" για να ελέγξουμε αν το σύμβολο που αναζητάμε είναι +το πρώτο ή το τελευταίο σύμβολο ενός string. Οι άγκυρες είναι δύο τύπων: +Πρώτα είναι το σύμβολο `^` που ελέγχει αν ο χαρακτήρας που ψάχνουμε είναι ο πρώτος +χαρακτήρας της εισόδου και μετά είναι το σύμβολο του δολαρίου `$` που ελέγχει αν ο χαρακτήρας που +ψάχνουμε είναι ο τελευταίος στο string εισόδου. + +### 2.8.1 Το Σύμβολο ^ + +Το σύμβολο `^` χρησιμοποιείται για να ελέγξουμε αν ο χαρακτήρας που ψάχνουμε είναι ο πρώτος χαρακτήρας +του string εισόδου. Αν δοκιμάσουμε την κανονική έκφραση `^a` (ψάχνουμε δηλαδή αν το a είναι το πρώτο +σύμβολο) στο string εισόδου `abc`, τότε βλέπουμε ότι όντως το `a` είναι ο πρώτος χαρακτήρας. Αλλά +αν δοκιμάσουμε την κανονική έκφραση `^b` στην παραπάνω είσοδο, τότε δεν θα πάρουμε κάποιο αποτέλεσμα. +Αυτό συμβαίνει επειδή στην έκφραση `abc` το "b" δεν είναι ο πρώτος χαρακτήρας. Ας ρίξουμε μια ματιά +στην κανονική έκφραση `^(T|t)he` η οποία ψάχνει για: έναν κεφαλαίο χαρακτήρα `T` ή έναν +πεζό χαρακτήρα `t` που να είναι ο πρώτος χαρακτήρας της εισόδου και να ακολουθείται από +έναν πεζό χαρακτήρα `h`, που ακολουθείται από έναν πεζό χαρακτήρα `e`. + ++"(T|t)he" => The car is parked in the garage. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/5ljjgB/1) + ++"^(T|t)he" => The car is parked in the garage. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/jXrKne/1) + +### 2.8.2 Το Δολάριο + +Το σύμβολο του δολαρίου `$` χρησιμοποιείται για να ελέγξουμε αν ο χαρακτήρας που αναζητάμε είναι ο τελευταίος +χαρακτήρας του string εισόδου. Για παράδειγμα, η κανονική έκφραση `(at\.)$` αναπαριστά: έναν +πεζό χαρακτήρα `a`, που ακολουθείται από έναν πεζό χαρακτήρα `t`, που ακολουθείται από μια τελεία `.` +και όλα αυτά πρέπει να είναι οι τελευταίοι χαρακτήρες της εισόδου. + ++"(at\.)" => The fat cat. sat. on the mat. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/y4Au4D/1) + ++"(at\.)$" => The fat cat. sat. on the mat. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/t0AkOd/1) + +## 3. Συντομογραφίες Συνόλων Χαρακτήρων + +Οι κανονικές εκφράσεις χρησιμοποιούν κάποιες συντομογραφίες για τα σύνολα χαρακτήρων που +χρησιμοποιούνται πιο συχνά και έτσι γίνονται πιο εύκολες και βολικές για τον χρήστη. +Οι συντομογραφίες των συνόλων χαρακτήρων είναι οι παρακάτω: + +|Συντομογραφία|Περιγραφή| +|:----:|----| +|.|Αναζήτηση όλων των χαρακτήρων εκτός από αυτόν για νέα γραμμή| +|\w|Αναζήτηση αλφαριθμητικών χαρακτήρων: `[a-zA-Z0-9_]`| +|\W|Αναζήτηση μη αλφαριθμητικών χαρακτήρων: `[^\w]`| +|\d|Αναζήτηση στα ψηφία: `[0-9]`| +|\D|Αναζήτηση χαρακτήρων που δεν είναι αριθμοί: `[^\d]`| +|\s|Αναζήτηση του χαρακτήρα του κενού: `[\t\n\f\r\p{Z}]`| +|\S|Αναζήτηση χαρακτήρων που δεν είναι το κενό: `[^\s]`| + +## 4. Αναζήτηση + +Η προς τα μπροστά και προς τα πίσω αναζήτηση, είναι συγκεκριμένοι τύποι συνόλων που +ονομάζονται ***non-capturing groups*** (Χρησιμοποιούνται για αναζήτηση κάποιου μοτίβου +αλλά δεν συμπεριλαμβάνονται στην λίστα των χαρακτήρων που ψάχνουμε). Οι αναζητήσεις προς τα μπροστά, χρησιμοποιούνται +όταν το μοτίβο έχει πριν ή μετά ένα ακόμη μοτίβο. Για παράδειγμα, αν θέλουμε να βρούμε όλους +τους αριθμούς που βρίσκονται μετά τον χαρακτήρα `$` στο παρακάτω string +`$4.44 and $10.88`, τότε θα χρησιμοποιήσουμε την κανονική έκφραση `(?<=\$)[0-9\.]*` +η οποία: βρίσκει όλους τους αριθμούς που βρίσκονται μετά από το σύμβολο`$` και περιέχουν τον χαρακτήρα `.` . +Παρακάτω μπορείτε να δείτε τους τύπους αναζήτησης στις κανονικές εκφράσεις: + +|Σύμβολο|Περιγραφή| +|:----:|----| +|?=|Θετική Αναζήτηση προς τα Μπροστά| +|?!|Αρνητική Αναζήτηση προς τα Μπροστά| +|?<=|Θετική Αναζήτηση προς τα Πίσω| +|? +"(T|t)he(?=\sfat)" => The fat cat sat on the mat. ++"(T|t)he(?!\sfat)" => The fat cat sat on the mat. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/V32Npg/1) + +### 4.3 Θετική Αναζήτηση προς τα Πίσω + +Η θετική αναζήτηση προς τα πίσω, χρησιμοποιείται όταν θέλουμε να βρούμε όλες τις εκφράσεις που +ταιριάζουν με ένα μοτίβο (που ορίζουμε εμείς) που βρίσκεται πριν από αυτές. Αυτή η αναζήτηση χρησιμοποιεί τα +σύμβολα `(?<=...)`. Για παράδειγμα, η κανονική έκφραση `(?<=(T|t)he\s)(fat|mat)`: +επιστρέφει όλες τις λέξεις `fat` ή `mat` που βρίσκονται μετά την λέξη `The` ή `the`. + ++"(?<=(T|t)he\s)(fat|mat)" => The fat cat sat on the mat. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/avH165/1) + +### 4.4 Αρνητική Αναζήτηση προς τα Πίσω + +Η αρνητική αναζήτηση προς τα πίσω χρησιμοποιείται όταν θέλουμε να βρούμε όλες τις εκφράσεις που +ταιριάζουν με το μοτίβο αναζήτησης, χωρίς όμως να υπάρχει άλλο μοτίβο (που ορίζουμε εμείς) πριν από αυτές. +Αυτή η αναζήτηση χρησιμοποιεί τα σύμβολα `(? +"(?<!(T|t)he\s)(cat)" => The cat sat on cat. ++"The" => The fat cat sat on the mat. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/dpQyf9/1) + ++"/The/gi" => The fat cat sat on the mat. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/ahfiuh/1) + +### 5.2 Καθολική Αναζήτηση + +Ο τροποποιητής `g`χρησιμοποιείται για καθολική αναζήτηση (για να βρεθούν δηλαδή όλες οι +περιπτώσεις που ταιριάζουν με το μοτίβο αναζήτησης και να μην σταματήσει στην πρώτη εύρεση). Για παράδειγμα, η +κανονική έκφραση `/.(at)/g` αναπαριστά: οποιονδήποτε χαρακτήρα εκτός από αυτόν για +νέα γραμμή, που ακολουθείται από τον πεζό χαρακτήρα `a`, που ακολουθείται από τον πεζό +χαρακτήρα `t` και αφού στο τέλος της κανονικής έκφρασης υπάρχει η σημαία `g`, +θα βρεθούν όλες οι περιπτώσεις που περιγράφονται από την παραπάνω κανονική έκφραση και όχι μόνο +η πρώτη (που είναι η προκαθορισμένη συμπεριφορά όταν δεν υπάρχει η σημαία `g`). + ++"/.(at)/" => The fat cat sat on the mat. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/jnk6gM/1) + ++"/.(at)/g" => The fat cat sat on the mat. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/dO1nef/1) + +### 5.3 Πολλές Γραμμές + +Ο τροποποιητής `m` χρησιμοποιείται για αναζήτηση σε πολλές γραμμές. Όπως είπαμε +προηγουμένως, οι άγκυρες `(^, $)` χρησιμοποιούνται για να ελέγξουμε αν ένα μοτίβο +βρίσκεται στην αρχή ή στο τέλος του string εισόδου. Αν θέλουμε οι άγκυρες αυτές να +ισχύουν για κάθε γραμμή, τότε χρησιμοποιούμε την σημαία `m`. Για παράδειγμα, η +κανονική έκφραση `/at(.)?$/gm` αναπαριστά: τον πεζό χαρακτήρα `a`, που ακολουθείται +από τον πεζό χαρακτήρα `t` και προαιρετικά οτιδήποτε άλλο εκτός από τον χαρακτήρα για +νέα γραμμή. Και αφού υπάρχει και η σημαία `m`, η κανονική έκφραση θα αναζητήσει +το μοτίβο στο τέλος κάθε γραμμής του string. + ++"/.at(.)?$/" => The fat + cat sat + on the mat. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/hoGMkP/1) + ++"/.at(.)?$/gm" => The fat + cat sat + on the mat. ++ +[Δοκιμή της κανονικής έκφρασης](https://regex101.com/r/E88WE2/1) + +## Contribution + +* Report issues +* Open pull request with improvements +* Spread the word +* Reach out to me directly at ziishaned@gmail.com or [](https://twitter.com/ziishaned) + +## License + +MIT © [Zeeshan Ahmad](https://twitter.com/ziishaned) diff --git a/translations/README-he.md b/translations/README-he.md new file mode 100644 index 00000000..411dccfe --- /dev/null +++ b/translations/README-he.md @@ -0,0 +1,577 @@ ++
+ +
+ ++ +
+ +## תרגומים: + +* [English](../README.md) +* [German](../translations/README-de.md) +* [Español](../translations/README-es.md) +* [Français](../translations/README-fr.md) +* [Português do Brasil](../translations/README-pt_BR.md) +* [中文版](../translations/README-cn.md) +* [日本語](../translations/README-ja.md) +* [한국어](../translations/README-ko.md) +* [Turkish](../translations/README-tr.md) +* [Greek](../translations/README-gr.md) +* [Magyar](../translations/README-hu.md) +* [Polish](../translations/README-pl.md) +* [Русский](../translations/README-ru.md) +* [Tiếng Việt](../translations/README-vn.md) +* [فارسی](../translations/README-fa.md) +* [עברית](../translations/README-he.md) + +## מה זה ביטוי רגולרי? + +\ No newline at end of file diff --git a/translations/README-hu.md b/translations/README-hu.md new file mode 100644 index 00000000..78c6ef86 --- /dev/null +++ b/translations/README-hu.md @@ -0,0 +1,557 @@ ++ +
+ +> ביטוי רגולרי (regular expression) הוא קבוצת תוים או סימנים אשר משמשים למציאת תבנית ספציפית בתוך טקסט. + +ביטוי רגולרי הוא תבנית המתאימה את עצמה לנושא במחרוזת משמאל לימין. +ביטויים רגולרים משמשים להחלפת טקסט בתוך מחרוזת, אימות טפסים, +חילוץ מחרוזת משנית ממחרוזת ראשית על בסיס התבנית המתאימה, ועוד. +המונח "Regular expression" (ביטוי רגולרי) הוא יחסית ארוך ולכן בדרך כלל +נמצא את המונח מקוצר ל-"regex" או "regexp". + +תדמיין.י שאת.ה כותב.ת אפליקציה ואת.ה רוצה להציב חוקים למצב בו המשתמש בוחר את +שם המשתמש. אנחנו רוצים לאפשר לשם המשתמש להכיל אותיות, מספרים, קוים תחתונים ומקפים. +בנוסף נרצה גם להגביל את מספר התוים בשם המשתמש בכדי שלא יראה מכוער. +נוכל להשתמש בביטוי הרגולרי הבא בכדי לאמת את שם המשתמש: + ++ +
+ ++
+ +הביטוי הרגולרי למעלה יכול לאשר את המחרוזות `john_doe`, `jo-hn_doe` +ו-`john12_as`. אך הוא לא יתאים למחרוזת `Jo` בגלל שמחרוזת זו מכילה אות גדולה + ובנוסף לכך היא קצרה מדי (פחות משלושה תוים). + +## תוכן עניינים + +- [התאמות בסיסיות](#1-התאמות-בסיסיות) +- [תווי-מטא](#2-תווי-מטא) + - [עצירה מלאה](#21-עצירה-מלאה) + - [מערכות תוים](#22-מערכות-תוים) + - [מערכות תוים שליליות](#221-מערכות-תוים-שליליות) + - [חזרות](#23-חזרות) + - [הכוכבית](#231-הכוכבית) + - [הפלוס](#232-הפלוס) + - [סימן השאלה](#233-סימן-השאלה) + - [סוגרים מסולסלים](#24-סוגרים-מסולסלים) + - [קבוצות לכידה](#25-קבוצות-לכידה) + - [קבוצות שאינן לוכדות](#251-קבוצות-שאינן-לוכדות) + - [חלופה](#26-חלופה) + - [התעלמות מתווים מיוחדים](#27-התעלמות-מתווים-מיוחדים) + - [עוגנים](#28-עוגנים) + - [ה-"קרט"](#281-ה-"קרט") + - [סימן הדולר](#282-סימן-הדולר) +- [קיצורי מערכות תווים](#3-קיצורי-מערכות-תווים) +- [הסתכלויות](#4-הסתכלויות) + - [מבט קדימה חיובי](#41-מבט-קדימה-חיובי) + - [מבט קדימה שלילי](#42-מבט-קדימה-שלילי) + - [מבט אחורה חיובי](#43-מבט-אחורה-חיובי) + - [מבט אחורה שלילי](#44-מבט-אחורה-שלילי) +- [דגלים](#5-דגלים) + - [חוסר רגישות לאותיות](#51-חוסר-רגישות-לאותיות) + - [חיפוש גלובלי](#52-חיפוש-גלובלי) + - [רב-שורות](#53-רב-שורות) +- [התאמה חמדנית מול עצלה](#6-התאמה-חמדנית-מול-עצלה) + +## 1. התאמות בסיסיות + +ביטוי רגולרי הוא בסף הכל תבנית של תוים שאנו משתמשים בהם בכדי לבצע חיפוש +בתוך הטקסט. לדוגמא, הביטוי הרגולרי `the` פירושו: האות `t`, ואחריה האות `h`, ואחריה האות `e`. + ++
+"the" => The fat cat sat on the mat. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/dmRygT/1) + +הביטוי הרגולרי `123` מתאים למחרוזת `123`. הביטוי הרגולרי מותאם למחרוזת קלט על ידי השוואת כל תו +בביטוי הרגולרי לכל תו במחרוזת הקלט, אחד אחרי השני. ביטויים רגולרים לרוב יהיו +תלויי אותיות קטנות או גדולות כך שהביטוי הרגולרי `The` לא יתאים למחרוזת `the`. + ++"The" => The fat cat sat on the mat. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/1paXsy/1) + +## 2. תווי-מטא + +תווי-מטא אלו הם אבני הבניין של ביטויים רגולרים. תווי-מטא לא מסמלים את עצמם, אלא מתפרשים באופן מיוחד. +לכמה תווי-מטא יש משמעויות מיוחדות והם נכתבים בתוך סוגריים מרובעים. +תווי-המטא הם כדלקמן: + +|תווי-מטא|תיאור| +|:----:|----| +|.|נקודה תואמת כל תו בודד למעט שבירת שורות.| +|[ ]|מחלקת תווים. תואם כל תו הכלול בין הסוגריים המרובעים.| +|[^ ]|מחלקת תווים שלילית. תואם כל תו שאינו כלול בין הסוגריים המרובעים| +|*|תואם 0 או יותר חזרות של התו הקודם.| +|+|תואם חזרה אחת או יותר של התו הקודם.| +|?|הופך את התו הקודם לאופציונלי.| +|{n,m}|סוגריים מסולסלים. תואם לפחות חזרות "n" אך לא יותר מ- "m" של התו הקודם.| +|(xyz)|קבוצת תווים. תואם את התווים xyz בסדר המדויק הזה.| +|||חלופה (או). התאמה בין התווים שלפני או לתווים שאחרי הסמל.| +|\|מתעלם מהתו הבא. זה מאפשר לך להתאים תווים שמורים[ ] ( ) { } . * + ? ^ $ \ |
| +|^|תואם את תחילת הקלט.| +|$|תואם את סוף הקלט.| + +## 2.1 עצירה מלאה + +עצירה מלאה `.` היר דוגמא פשוטה לשימוש בתו-מטא. תו-המטא `.` מתאים לכל תו בודד. הוא לא יתאים +לתו return (\r) או לתו newline (\n). למשל, הביטוי הרגולרי `.ar` פירושו: כל תו, שאחריו האות `a`, ואחריה האות `r`. + ++".ar" => The car parked in the garage. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/xc9GkU/1) + +## 2.2 מערכות תוים + +מערכות תוים נקראים גם מחלקות תוים. סוגריים מרובעים משמשים לציון מערכות תוים. +השתמש במקף בתוך ערכת התוים בכדי לציין את טווח התוים. סדר טווח התוים לא משנה. +לדוגמא, הביטוי הרגולרי `[Tt]he` פירושו: אות גדולה +`T` או אות קטנה `t`, שאחריה מופיעה האות `h`, ואחריה מופיעה האות `e`. + ++"[Tt]he" => The car parked in the garage. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/2ITLQ4/1) + +נקודה בתוך ערכת התוים בשונה מבחוץ תחשב כתו נקודה. הביטוי הרגולרי +`ar[.]` פירושו: תו האות הקטנה `a`, שאחריו האות `r`, +ואחריה התו נקודה `.`. + ++"ar[.]" => A garage is a good place to park a car. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/wL3xtE/1) + +### 2.2.1 מערכות תוים שליליות + +באופן כללי, הסימן "קרט"(גג) מייצג את תחילתה של מחרוזת, אך במידה והוא מוקלד לאחר סוגר מרובע פותח, +הוא שולל את מערכת ההתוים שיהיו תחת אותם סוגרים. לדוגמא, הביטוי הרגולרי `[^c]ar` פירושו: כל תו חוץ מ-`c`, +שלאחריו יופיע התו `a`, שאחריו יופיע התו `r`. + ++"[^c]ar" => The car parked in the garage. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/nNNlq3/1) + +## 2.3 חזרות + +תווי-המטא `+`, `*` או `?` משמשים לציון כמה פעמים דפוסי משני יכולים להתרחש. +תווי-מטא אלו פועלים אחרת במצבים שונים. + +### 2.3.1 הכוכבית + +הסימן - `*` תואם אפס או יותר חזרות של המתאם הקודם. הביטוי הרגולרי `a*` פירושו: +אפס או יותר חזרות של התו הקודם- `a`. אבל אם הכוכבית תופיע לאחר מערכת או מערך תוים אז +הוא ימצא את החזרות של מערכת התוים כולה. לדוגמא, הביטוי הרגולרי `[a-z]*` פירושו: +כל מספר של אותיות קטנות בשורה. + ++"[a-z]*" => The car parked in the garage #21. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/7m8me5/1) + +הסימן - `*` יכול לשמש יחד עם התו-מטא `.` בכדי להתאים כל מחרוזת תוים `.*`. +הסימון - `*` יכול לשמש יחד עם התו רווח - `\s` בכדי להתאים מחרוזת של תוי רווח. +לדוגמא, הביטוי `\s*cat\s*` פירושו: אפס או יותר רווחים, שאחריהם תופיעה האות הקטנה `c`, +שאחריה תופיע האות הקטנה `a`, ואחריה האות הקטנה `t`, ולבסוף אחריה יופיעו אפס או יותר תווי רווח. + ++"\s*cat\s*" => The fat cat sat on the concatenation. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/gGrwuz/1) + +### 2.3.2 הפלוס + +הסימן `+` מתאים לאחת או יותר חזרות של התו הקודם לו. לדוגמא, הביטוי הרגולרי + `c.+t` פירושו: האות הקטנה - `c`, לאחריה לפחות תו אחד או יותר, + ואחריה האות הקטנה `t`. חשוב לציין שה - `t` יהיה התו `t` האחרון במשפט. + ++"c.+t" => The fat cat sat on the mat. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/Dzf9Aa/1) + +### 2.3.3 סימן השאלה + +בביטוי רגולרי, התו-מטא `?` הופך את התו הקודם לאופציונלי, +סמל זה יתאים לאפס או יותר הופעות של אותו תו קודם. לדוגמא, הביטוי הרגולרי +`[T]?he` פירושו: אופציה לאות +`T` גדולה, ולאחריה אות קטנה `h`, ולאחריה תופיע האות - `e`. + ++"[T]he" => The car is parked in the garage. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/cIg9zm/1) + ++"[T]?he" => The car is parked in the garage. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/kPpO2x/1) + +## 2.4 סוגרים מסולסלים + +בביטויים רגולרים, סוגרים מסולסלים (נקראים גם מכמתים) משמשים לציון +מספר הפעמים שניתן לחזור על תו או קבוצת תוים מסויימת. לדוגמא, הביטור הרגולרי + `[0-9]{2,3}` פירושו: התאם לפחות שתי ספרות, אבל לא יותר משלוש, בטווח שבין 0 ל-9 + ++"[0-9]{2,3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/juM86s/1) + +אנחנו יכולים לוותר על המספר השני בסוגרים המסולסלים. לדוגמא, בביטוי הרגולרי +`[0-9]{2,}` פירושו: התאמת שתי ספרות או יותר. בנוסף אם +נוריד את הפסיק, לדוגמא בביטוי הרגולרי `[0-9]{3}` פירושו: +התאם בדיוק שלוש ספרות. + ++"[0-9]{2,}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/Gdy4w5/1) + ++"[0-9]{3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/Sivu30/1) + +## 2.5 קבוצות לכידה + +קבוצה מלכדת היא קבוצה של תת-תבניות שנכתבות בתוך סוגריים רגילים `(...)` . +כפי שצויין קודם לכן, בביטוי רגולרי, אם נניח מכמת אחרי תו הוא יחזור על התו הקודם. +אבל אם נניח מכמת אחרי קבוצה מלכדת אז המכמת יתיחס לכל הקבוצה המלכדת. לדוגמא, הביטוי הרגולרי +`(ab)*` תואם אפס או יותר חזרות של המחרוזת "ab". אנחנו יכולים גם להשתמש +בתו-מטא `|` המשמש לבצע את הפעולה 'OR'(או) בתוך קבוצה מלכדת. +לדוגמא, הביטוי הרגולרי `(c|g|p)ar` פירושו: אות קטנה `c`, +`g` או `p`, שאחריהן תופיע האות `a`, ואחריה האות `r`. + ++"(c|g|p)ar" => The car is parked in the garage. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/tUxrBG/1) + +יש לשים לב כי קבוצות מלכדות לא רק תואמות, אלא גם תופסות את התוים לשימוש בשפת האם. +שפת האם יכולה להיות Python או JavaScript או כמעט כל שפה שמיישמת ביטויים רגולרים +בבגדרת פונקציה. + +### 2.5.1 קבוצות שאינן לוכדות + +קבוצה שאינה מלכדת זוהי קבוצת לוכדת התואמת את התוים אבל לא תופסת את הקבוצה. +קבוצה שאינה מלכדת מסומנת על ידי התו `?` ואחריו `:` בתוך הסוגריים הרגילים. `(...)`. +לדוגמא, בביטוי הרגולרי `(?:c|g|p)ar` שדומה ל-`(c|g|p)ar` +בכך שהוא תואם לאותם תווים אך לא ייצר קבוצת לכידה. + ++"(?:c|g|p)ar" => The car is parked in the garage. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/Rm7Me8/1) + +קבוצות שאינן מלכדות יכולות להיות שימושיות כאשר יש צורך בפונקציונליות של חיפוש והחלפה +או כאשר מעורבת גם קבוצת לכידה בכדי לשמור על הסקירה כאשר מפיקים כל סוג אחר של פלט. +ניתן לראות גם ב [4. Lookaround](#4-lookaround). + +## 2.6 חלופה + +בביטוי רגולרי, הקו ניצב `|` משמש בכדי להגדיר חלופה. חלופה היא כמו הצהרת OR (או) +בין ביטויים שונים. כעט את.ה עלול לחשוב שמערכות התווים והתו המשמש להגדרת חלופה יעבדו באותה הדרך. +אך ההבדל העיקרי בין מערכת תווים לבין חלופה הוא שמערכת תווים פועלת ברמת התו והחלופה +עובדת ברמת הביטוי. לדוגמא, הביטוי הרגולרי `(T|t)he|car` פירושו: או (אות גדולה `T` או אות קטנה +`t`, שלאחריהן אות קטנה `h`, שאחריה אות קטנה `e`) או (אות קטנה `c`, שאחריה תופיע האות `a`, +ולאחריה תופיע האות `r`). יש לשים לב שהכללתי את הסוגריים לשם ההבהרה, +בכדי להראות שאפשר להתמודד עם כל ביטוי בסוגריים והוא יתאים. + ++"(T|t)he|car" => The car is parked in the garage. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/fBXyX0/1) + +## 2.7 התעלמות מתווים מיוחדים + +לוכסן שמאלי `\` משמש בביטוי רגולרי בכדי להתעלם מהתו הבא. זה מאפשר לנו לכלול תוים שמורים כמו +`{ } [ ] / \ + * . $ ^ | ?` כתוים להתאמות. הכדי להשתמש בתוים המיוחדים הללו התו התאמה, +יש להוסיף אותו מראש עם `\` לפניו. לדוגמא, הביטוי הרגולרי `.` משמש בכדי להתאים כל תו חוץ משורה חדשה. +כעט בכדי לבצע התאמה עם הסימן `.` במחרוזת קלט, יהיה צורך בהוספת הלוכסן השמאלי. למשל בביטוי הרגולרי +`(f|c|m)at\.?` פירושו: אות קטנה `f`, `c` או `m`, שאחריהן תופיע האות הקטנה +`a`, ואחריה תופיע האות הקטנה `t`, ולבסוף יופיע באופן אופציונלי התו - `.`. + ++"(f|c|m)at\.?" => The fat cat sat on the mat. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/DOc5Nu/1) + +## 2.8 עוגנים + +בביטויים רגולרים, אנחנו משתמשים בעוגנים בכדי לבדוק אם סימן ההתאמה הוא סימן התחלה או +סימן סיום של מחרוזת הקלט. ישנם שני סוגי עוגנים: +הסוג הראשון הוא ה"קרט"(גג) `^` שבודק אם תו תואם הוא התו הראשון של הקלט והסוג השני הוא סימן הדולר +`$` אשר בודק אם תו תואם הוא התו האחרון שבקלט + +### 2.8.1 ה-"קרט" + +הסימן "קרט" `^` משמש לבדיקה אם תו תואם הוא התו הראשון של מחרוזת הקלט. +אם ניישם את הביטור הרגולרי הבא `^a` (כלומר 'a' חייב להיות התו ההתחלתי) +המחרוזת `abc`, תתאים לדרישות `a`. +אך אם ניישם את הביטוי הרגולרי `^b` על במחרוזת למעלה, היא לא תמצא אף התאמה. +בגלל שבמחרוזת `abc`, ה-"b" אינו תו התחלתי. בואו נסתכל על ביטוי רגולרי אחר +`^(T|t)he` שפירושו: אות גדולה `T` או אות קטנה `t` חייבת להיות התו הראשון של המחרוזת, +ואחריה האות הקטנה `h`, ולאחריה האות הקטנה `e`. + ++"(T|t)he" => The car is parked in the garage. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/5ljjgB/1) + ++"^(T|t)he" => The car is parked in the garage. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/jXrKne/1) + +### 2.8.2 סימן הדולר + +סימן הדולר `$` משמש בכדי לבדוק אם התו התואם הוא התו האחרון במחרוזת. לדוגמא, +הביטוי הרגולרי `(at\.)$` פירושו: האות הקטנה `a`, שאחריה תיהיה האות הקטנה `t`, ואחריה התו נקודה `.` +וכל ההתאמה חייבת לביות בסופה של המחרוזת. + ++"(at\.)" => The fat cat. sat. on the mat. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/y4Au4D/1) + ++"(at\.)$" => The fat cat. sat. on the mat. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/t0AkOd/1) + +## 3. קיצורי מערכות תווים + +ישנם מספר קיצורים נוחים למערכות תווים נפוצות / ביטויים רגולרים: + +|קיצור|תיאור| +|:----:|----| +|.|תואם כל תו חוץ מתחילת שורה חדשה| +|\w|תואם תוים אלפא-נומריים (אותיות ומספרים): `[a-zA-Z0-9_]`| +|\W|תואם תוים לא אלפא-נומריים: `[^\w]`| +|\d|תואם ספרות: `[0-9]`| +|\D|תואם תוים שאינם ספרות: `[^\d]`| +|\s|תואם תוי רווח: `[\t\n\f\r\p{Z}]`| +|\S|תואם תוים שאינם רווח: `[^\s]`| + +## 4. הסתכלויות + +מבט לאחור ומבט לפנים (נקראים גם הסתכלויות) אלו הם סוגים ספציפים של קבוצות שאינן לוכדות. +(משמשות בכדי להתאים תבנית אך ללא הכנסתה לרשימת ההתאמות). +הסתכלויות משמשות כאשר יש להקדים תבנית בכך שזו תלויה בתבנית אחרת בכדי שהראשונה תתאים. +לדוגמא, תדמיין.י שאנחנו רוצים לקבל את כל המספרים שלפניהם יש את התו `$` מהמחרוזת +`$4.44 and $10.88`. אנחנו נשתמש בביטוי הרגולרי הבא: +`(?<=\$)[0-9\.]*` שפירושו: התאם את כל הספרות או התו `.` שלפני ההתאמה +קיים התו `$`. בטבלה מטה מוצגים סוגי המבטים המשמשים ביטויים רגולרים: + +|סימן|תיאור| +|:----:|----| +|?=|מבט קדימה חיובי| +|?!|מבט קדימה שלילי| +|?<=|מבט אחורה חיובי| +|?|מבט אחורה שלילי| + +### 4.1 מבט קדימה חיובי + +מבט קדימה חיובי דורש שבחלקו הראשון של ביטוי חייב להתקיים הביטוי מבט קדימה חיובי. +ההתאמה המוחזרת מכילה רק את הטקסט המתאים לחלק הראשון של הביטוי לפני המבט קדימה. +בכדי להגדיר מבט קדימה חיובי, משתמשים בסוגריים. בתוך הסוגריים, משתמשים בסימן שאלה +ואחריו סימן השוואה כך: `(?=...)`. ביטויי המבט קדימה נכתבים אחרי סימני סוג +המבט בתוך הסוגריים. לדוגמא, הביטוי הרגולרי `(T|t)he(?=\sfat)` פירושו: +התאם או את האות הקטנה `t` או את האות הגדולה `T`, שאחריה תיהיה האות `h`, ואחריה האות `e`. +בסוגריים אנחנו מגדירים מבט קדימה חיובי שאומר למנוע של הביטוי הרגולרי להתאים `The` או `the` +רק אם אחרי ההתאמה מופיעה המחרוזתS ` fat`. + ++"(T|t)he(?=\sfat)" => The fat cat sat on the mat. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/IDDARt/1) + +### 4.2 מבט קדימה שלילי + +משתמשים במבט קדימה שלילי כשאנחנו צריכים לקבל את כל ההתאמות ממחרוזת קלט שלאחריהן אין תבנית מסויימת. +מבט קדימה שלילי יכתב באותה הדרך כמו שנכתב המבט קדימה החיובי. ההבדל היחיד הוא שמבקום +סימן השווה `=`, עלינו להשתמש בסימן קריאה `!` בכדי לציין את השלילה כלומר: `(?!...)`. +בואו נסתכל על הביטוי הרגולרי הבא `(T|t)he(?!\sfat)` שפירושו: התאם את כל המילים `The` או `the` +ממחרוזת קלט שאחריהן אין את התו רווח ולאחר מכן את המילה `fat`. + ++"(T|t)he(?!\sfat)" => The fat cat sat on the mat. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/V32Npg/1) + +### 4.3 מבט אחורה חיובי + +משתמשים במבט אחורה חיובי בכדי לקבל את כל ההתאמות שלפניהן יש תבנית ספציפית מסויימת. +מבטים אחורה חיוביים נכתבים כך: `(?<=...)`. לדוגמא, +הביטוי הרגולרי `(?<=(T|t)he\s)(fat|mat)` פירושו: התאם +את כל המילים `fat` או `mat` ממחרוזת קלט שנמצאות לפני המילים `The` או `the` ויש רווח +שמפריד בינהן. + ++"(?<=(T|t)he\s)(fat|mat)" => The fat cat sat on the mat. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/avH165/1) + +### 4.4 מבט אחורה שלילי + +משתמשים במבט אחורה שלילי בכדי לקבל את כל ההתאמות שלפניהן אין תבנית ספציפית מסויימת. +מבטים אחורה שליליים יכתבו כך: `(?. לדוגמא, הביטוי הרגולרי +`(? פירושו: התאם את כל המילים `cat` +ממחרוזת קלט שלא נמצאות אחרי המילים `The` or `the` כאשר רווח מפריד בינהן. + ++"(?<!(T|t)he\s)(cat)" => The cat sat on cat. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/8Efx5G/1) + +## 5. דגלים + +דגלים נקראים גם משנים בגלל שהם משנים את הפלט של הביטוי הרגולרי. +ניתן להשתמש בדגלים הללו בכל סדר או שילוב והם חלק בלתי נפרד +מהביטוי הרולרי (RegExp). + +|דגל|תיאור| +|:----:|----| +|i|חוסר רגישות לאותיות: ההתאמה לא תהיה רגישה לאותיות קטנות או גדולות.| +|g|חיפוש גלובלי: התאם את כל ההאמות שהופיעו, לא רק את הראשונה.| +|m|רב-שורות: תווי-המטא העוגנים (`$` או `^`) עובדים על כל שורה.| + +### 5.1 חוסר רגישות לאותיות + +המשנה `i` משמש בכדי לבצע התאמות חסרות רגישות לאותיות קטנות או גדולות. +לדוגמא, בביטוי הרגולרי `/The/gi` פירושו: אות גדולה `T`, ואחריה אות קטנה +`h`, ואחריה אות קטנה `e`. ובסוף הביטוי הרגולרי יש את הדגל `i` שאומר למנוע הביטוי הרגולרי +להתעלם מהבדלי אותיות גדולות או קטנות. וכפי שאת.ה יכול לראות, +סיפקנו גם דגל `g` בגדלל שאנחנו רוצים לחפש את התבנית בכל מחרוזת הקלט. + ++"The" => The fat cat sat on the mat. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/dpQyf9/1) + ++"/The/gi" => The fat cat sat on the mat. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/ahfiuh/1) + +### 5.2 חיפוש גלובלי + +המשנה `g` משמש בכדי לבצע התאמות גלובליות (מוצא את כל ההתאמות במקום לעצור בהתאמה הראשונה). +לדוגמא, בביטוי הרגולרי `/.(at)/g` פירושו: כל תו חות משורה חדשה, שאחריו תיהיה האות הקטנה `a`, +ואחריה תיהיה האות הקטנה `t`. בגלל שסיפקנו את הדגל `g` בסופו של הביטוי הרגולרי, +הוא עכשיו ימצא את כל ההתאמות במחרוזת הקלט, לא רק את ההתאמה הראשונה (שזו התנהגות ברירת המחדל). + ++"/.(at)/" => The fat cat sat on the mat. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/jnk6gM/1) + ++"/.(at)/g" => The fat cat sat on the mat. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/dO1nef/1) + +### 5.3 רב-שורות + +המשנה `m` משמש בכדי לבצע התאמות במספר רב של שורות. כפי שדנו על כך קודם לכן, +העוגנים `(^, $)` משמשים לבדיקה אם תבנית היא בהתחלה או בסופו של קלט. +אבל אם אנחנו רוצים שהעוגנים הללו יעבדו על כל שורה, אנחנו נשתמש בדגל `m`. לדוגמא, +בביטוי הרגולרי `/at(.)?$/gm` פירושו: אות קטנה +`a`, שלאחריה האות הקטנה `t` וכאופציה, כל תו שאינו שורה חדשה. ובגלל הדגל `m`, +המנוע של הביטוי הרגולרי יתאים את התבנית בכל סוף שורה במחרוזת. + ++"/.at(.)?$/" => The fat + cat sat + on the mat. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/hoGMkP/1) + ++"/.at(.)?$/gm" => The fat + cat sat + on the mat. ++ +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/E88WE2/1) + +## 6. התאמה חמדנית מול עצלה + +כברירת מחדל, ביטוי רגולרי יבצע התאמה חמדנית, זאת אומרת שביצוע ההתאמה תיהיה ארוכה ככל הניתן. +אנחנו יכולים להשתמש ב-`?` בכדי לבצע התאמה בצורה עצלה, פירוש הדבר שההתאמה תיהיה קצרה ככל שניתן. + ++"/(.*at)/" => The fat cat sat on the mat.+ + +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/AyAdgJ/1) + ++"/(.*?at)/" => The fat cat sat on the mat.+ + +[בדוק.י את הביטוי הרגולרי](https://regex101.com/r/AyAdgJ/2) + + +## תרומה + +* Open a pull request with improvements +* Discuss ideas in issues +* Spread the word +* Reach out with any feedback +* [](https://twitter.com/ziishaned) + +## רישיון + +MIT © [Zeeshan Ahmad](https://twitter.com/ziishaned) ++
+ + + +## Fordítások: + +* [English](../README.md) +* [German](../translations/README-de.md) +* [Español](../translations/README-es.md) +* [Français](../translations/README-fr.md) +* [Português do Brasil](../translations/README-pt_BR.md) +* [中文版](../translations/README-cn.md) +* [日本語](../translations/README-ja.md) +* [한국어](../translations/README-ko.md) +* [Turkish](../translations/README-tr.md) +* [Greek](../translations/README-gr.md) +* [Magyar](../translations/README-hu.md) +* [Polish](../translations/README-pl.md) +* [Русский](../translations/README-ru.md) +* [Tiếng Việt](../translations/README-vn.md) +* [فارسی](../translations/README-fa.md) +* [עברית](../translations/README-he.md) + +## Mi az a reguláris kifejezés? + +[](https://gum.co/learn-regex) + +> A reguláris kifejezés karakterek vagy szimbólumok egy csoportja, amelyet egy szövegből adott minták megtalálására használnak. + +A reguláris kifejezés egy olyan minta, amely illeszkedik egy adott karakterláncra +balról jobbra. Magát a "Regular expression" kifejezést általában rövidítve lehet +megtalálni, mint "regex" vagy "regexp". A reguláris kifejezést használják szövegrészek +lecserélésére egy szövegben, űrlapok validálására, szövegrészek kiválasztására +mintaegyezés alapján egy hosszabb szövegből és így tovább. + +Képzeld el, hogy egy alkalmazást írsz és szeretnél szabályokat állítani a felhasználónév +kiválasztásához. A felhasználónév csak betűket, számokat, aláhúzásjelet és kötőjelet +tartalmazhat. Szeretnénk limitálni a karakterek maximális számát is a felhasználónévben, +hogy ne legyen csúnya. A felhasználónév validálására a következő reguláris kifejezést +használjuk: + +
+ ++ +
+
++
+ +A feljebbi reguláris kifejezés elfogadja a `john_doe`, `jo-hn_doe` és a +`john12_as` karakterláncokat. Nem fog egyezni a `Jo`-ra mert ez nagybetűt +tartalmaz és túl rövid is. + +## Tartalomjegyzék + +- [Bevezetés](#1-bevezetés) +- [Meta karakterek](#2-meta-karakterek) + - [Full stop](#21-full-stop) + - [Karakter osztályok](#22-karakter-osztályok) + - [Negált karakter osztályok](#221-negált-karakter-osztályok) + - [Ismétlések](#23-ismétlések) + - [A csillag](#231-a-csillag) + - [A plusz](#232-a-plusz) + - [A kérdőjel](#233-a-kérdőjel) + - [A kapcsos zárójelek](#24-a-kapcsos-zárójelek) + - [Karakter csoportok](#25-karakter-csoportok) + - [Alternálás](#26-alternálás) + - [Speciális karakter escape-elése](#27-speciális-karakter-escape-elése) + - [Horgonyok](#28-horgonyok) + - [Kalap](#281-kalap) + - [Dollár](#282-dollár) +- [Shorthand Karakter osztályok](#3-shorthand-karakter-osztályok) +- [Lookaround](#4-lookaround) + - [Positive Lookahead](#41-positive-lookahead) + - [Negative Lookahead](#42-negative-lookahead) + - [Positive Lookbehind](#43-positive-lookbehind) + - [Negative Lookbehind](#44-negative-lookbehind) +- [Flag-ek](#5-flag-ek) + - [Kis-nagybetű érzéketlen](#51-kis-nagybetű-érzéketlen) + - [Globális keresés](#52-globális-keresés) + - [Többsoros](#53-többsoros) + +## 1. Bevezetés + +A reguláris kifejezés egy karakterminta, amit keresésre használunk egy +szövegben. Például a `the` reguláris kifejezés a következőt jelenti: egy `t` betű, +amit `h` követ, amit egy `e` követ. + ++
+"the" => The fat cat sat on the mat. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/dmRygT/1) + +Az `123` reguláris kifejezés illeszkedik a `123` karakterláncra. A reguláris kifejezés +minden egyes karaktere össze lesz hasonlítva a bevitt karakterlánc minden elemével +egymás után. A reguláris kifejezések alap esetben kis-nagybetű érzékenyek, tehát a +`The` reguláris kifejezés nem fog illeszkedni a `the` karakterláncra. + ++"The" => The fat cat sat on the mat. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/1paXsy/1) + +## 2. Meta karakterek + +A meta karakterek a reguláris kifejezések építőkockái. A meta karakterek speciális +módon értelmezendőek. Némelyik meta karakternek speciális jelentése van és +szögletes zárójelek közé vannak téve. A meta karakterek a következők: + +|Meta karakter|Leírás| +|:----:|----| +|.|A pont illeszkedik minden egyes karakterre kivéve a sortörést.| +|[ ]|Karakter osztály. Minden karakterre illeszkedik ami a szögletes zárójelek közt van.| +|[^ ]|Negált karakter osztály. Minden karakterre illeszkedik ami nincs a szögletes zárójelek közt.| +|*|Illeszkedik az őt megelőző szimbólum 0 vagy több ismétlődésére.| +|+|Illeszkedik az őt megelőző szimbólum 1 vagy több ismétlődésére.| +|?|Opcionálissá teszi az őt megelőző szimbólumot.| +|{n,m}|Kapcsos zárójelek. Illeszkedik az őt megelőző szimbólum minimum "n" de nem több mint "m" ismétlődésére.| +|(xyz)|Karakter csoport. Illeszkedik az xyz karakterekre pontosan ilyen sorrendben.| +|||Alternáció. Illeszkedik a szimbólum előtt és után álló karakterekre is.| +|\|Escape-li a következő karaktert. A segítségével lefoglalt karakterekre is lehet illeszkedni[ ] ( ) { } . * + ? ^ $ \ |
| +|^|A karakterlánc elejére illeszkedik.| +|$|A karakterlánc végére illeszkedik.| + +## 2.1 Full stop + +A full stop `.` a legegyszerűbb meta karakter példa. A `.` meta karakter illeszkedik +minden egyes karakterre. Nem fog illeszkedni a kocsi vissza és a sortörés karakterekre. +Például a `.ar` reguláris kifejezés jelentése: minden karakter, amit `a` aztán `r` követ. + ++".ar" => The car parked in the garage. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/xc9GkU/1) + +## 2.2 Karakter osztályok + +A szögletes zárójelekkel határozzuk meg a karakter osztályokat. A szögletes +zárójelek közt kötőjel karakterrel határozhatunk meg karakter tartományokat. +A karaktertartomány sorrendje nem számít. Például a `[Tt]he` reguláris kifejezés +jelentése: nagybetűs `T` vagy kisbetűs `t` amit egy `h` majd egy `e` betű követ. + ++"[Tt]he" => The car parked in the garage. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/2ITLQ4/1) + +Egy pont a karakter osztályon belül egyébként szó szerint pont-ot jelent. A +`ar[.]` reguláris kifejezés jelentése: kisbetűs `a` amit egy `r` aztán egy +pont `.` karakter követ. + ++"ar[.]" => A garage is a good place to park a car. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/wL3xtE/1) + +### 2.2.1 Negált karakter osztályok + +Általában a kalap szimbólum egy karakterlánc elejét jelenti, de ha egy nyitó +szögletes zárójel után áll, akkor negálja a karakter osztályt. Például a +`[^c]ar` reguláris kifejezés jelentése: minden karakter a `c` kivételével +ami után `a` aztán egy `r` betű áll. + ++"[^c]ar" => The car parked in the garage. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/nNNlq3/1) + +## 2.3 Ismétlések + +A következő meta karaktereket `+`, `*` vagy `?` arra használjuk, hogy meghatározzuk, +hányszor fordulhat elő az al-minta. Ezek a meta karakterek máshogy viselkednek +adott helyzetekben. + +### 2.3.1 A csillag + +A `*` szimbólum az őt megelőző karakter nulla vagy több ismétlődésére illeszkedik. +A `a*` reguláris kifejezés jelentése: nulla vagy több ismétlődése az őt megelőző `a` +karakternek. De ha egy karakter osztály után áll akkor az egész karakterosztály +ismétlődését keresi. Például, a `[a-z]*` reguláris kifejezés jelentése: bármennyi +kisbetűs betű egy sorban. + ++"[a-z]*" => The car parked in the garage #21. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/7m8me5/1) + +A `*` szimbólum használható a `.` meta karakterrel `.*`, ez illeszkedik +bármilyen karakterláncra. A `*` szimbólum használható a whitespace karakterrel `\s` +együtt, hogy illeszkedjen egy whitespace-ekből álló karakterláncra. Például a +`\s*cat\s*`kifejezés jelentése: nulla vagy több szóköz, amit egy kisbetűs `c`, +aztán egy kisbetűs `a`, aztán egy kisbetűs `t`, amit még nulla vagy több szóköz követ. + ++"\s*cat\s*" => The fat cat sat on the concatenation. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/gGrwuz/1) + +### 2.3.2 A plusz + +A `+` szimbólum illeszkedik az őt megelőző karakter egy vagy több ismétlődésére. +Például a `c.+t` kifejezés jelentése: kisbetűs `c` betű, amit legalább egy vagy +több `t` követ. Itt tisztázni kell hogy a `t` az utolsó `t` a mondatban. + ++"c.+t" => The fat cat sat on the mat. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/Dzf9Aa/1) + +### 2.3.3 A kérdőjel + +A reguláris kifejezésben a `?` meta karakter opcionálissá teszi az őt +megelőző karaktert. Ez a szimbólum az őt megelőző karakter nulla vagy egy +példányára illeszkedik. Például a `[T]?he` kifejezés jelentése: opcionális a +nagybetűs `T`, amit egy kisbetűs `h`, majd egy kisbetűs `e` követ. + ++"[T]he" => The car is parked in the garage. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/cIg9zm/1) + ++"[T]?he" => The car is parked in the garage. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/kPpO2x/1) + +## 2.4 A kapcsos zárójelek + +A reguláris kifejezésben a kapcsos zárójeleket annak meghatározására használjuk, +hogy egy karakter vagy egy karakter csoport hányszor ismétlődhet. Például a +`[0-9]{2,3}` kifejezés jelentése: minimum 2 de nem több mint 3 karakter a `[0-9]` +karaktertartományon belül. + ++"[0-9]{2,3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/juM86s/1) + +Kihagyhatjuk a második számot. Például a `[0-9]{2,}` kifejezés jelentése: +2 vagy több számra illeszkedik. Ha a vesszőt is kitöröljük `[0-9]{3}`: Pontosan +3 számra illeszkedik. + ++"[0-9]{2,}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/Gdy4w5/1) + ++"[0-9]{3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/Sivu30/1) + +## 2.5 Karakter csoportok + +A karakter csoport al-minták csoportja amik zárójelek közé `(...)` vannak írva. +Ahogy előbb már megbeszéltük, ha egy karakter után ismétlő karaktert rakunk, az +ismételni fogja az előtte lévő karaktert. De ha egy ismétlő karaktert egy karakter +csoport után rakunk, az ismételni fogja az egész csoportot. Például a `(ab)*` +kifejezés illeszkedik nulla vagy több ismétlődésére az `ab` karaktereknek. +Használhatunk alternáló meta karaktert `|` is a csoporton belül. Például a `(c|g|p)ar` +kifejezés jelentése: kisbetűs `c`, `g` vagy `p` karakter, amit egy `a` aztán +egy `r` karakter követ. + ++"(c|g|p)ar" => The car is parked in the garage. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/tUxrBG/1) + +## 2.6 Alternálás + +A reguláris kifejezésben a függőleges vonalat `|` alternálásra (választásra) +használjuk. Az alternálás olyan, mint egy feltétel több kifejezés közt. Most +azt gondolhatod, hogy a karakter osztály és az alternáció ugyan úgy működik. +De a fő különbség köztük, hogy a karakter osztály a karakterek szintjén működik, +az alternáció viszont a kifejezés szintjén. Például a `(T|t)he|car` kifejezés +jelentése: nagybetűs `T` karakter vagy kisbetűs `t` karakter, amit egy `h` és +egy `e` követ, VAGY kisbetűs `c` aztán `a` aztán `r` karakter. + ++"(T|t)he|car" => The car is parked in the garage. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/fBXyX0/1) + +## 2.7 Speciális karakter escape-elése + +A visszaper `\` a reguláris kifejezésekben a következő karakter escape-elésére +való. Ez enged nekünk szimbólumokat vagy lefoglalt karaktereket `{ } [ ] / \ + * . $ ^ | ?` +megadni. Egy speciális karakter egyező karakterként való megadásához tedd elé +a `\` karaktert. + +Például a `.` kifejezést az összes karakter, kivéve a sortörés illeszkedéséhez +használjuk. A `(f|c|m)at\.?` kifejezés jelentése: kisbetűs `f`, `c` vagy `m`, amit +egy kisbetűs `a` aztán egy kisbetűs `t`, amit egy opcionális `.` karakter követ. + ++"(f|c|m)at\.?" => The fat cat sat on the mat. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/fBXyX0/1) + +## 2.8 Horgonyok + +A reguláris kifejezésekben horgonyokat használunk, hogy megnézzük, az illeszkedő +szimbólum a kezdő vagy a záró szimbóluma-e a karakterláncnak. A horgonyoknak két +fajtájuk van: Az első a Kalap `^`, ami megnézi, hogy az egyező karakter a karakterlánc +kezdő kerektere-e és a második a Dollár `$`, ami azt vizsgálja, hogy az egyező +karakter a karakterlánc utolsó karaktere-e. + +### 2.8.1 Kalap + +A kalap `^` szimbólumot arra használjuk, hogy megnézzük, hogy az egyező karakter +a karakterlánc kezdő kerektere-e. Ha megadjuk a következő kifejezést: `^a`, +akkor illeszkedik a `abc` karakterlánc `a` karakterére, mert az za első. De ha +megadjuk, hogy: `^b`, ez nem fog illeszkedni az `abc` egyik részére sem, mert +nem `b` a kezdő karakter. Nézzünk meg egy másik kifejezést. `^(T|t)he` jelentése: +nagybetűs `T` vagy kisbetűs `t` a kezdő karaktere a karakterláncnak, amit kisbetűs +`h`, majd kisbetűs `e` követ. + ++"(T|t)he" => The car is parked in the garage. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/5ljjgB/1) + ++"^(T|t)he" => The car is parked in the garage. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/jXrKne/1) + +### 2.8.2 Dollár + +A dollár `$` szimbólumot arra használjuk, hogy megnézzük, hogy az egyező +karakter a karakterlánc utolsó karaktere-e. Például a `(at\.)$` kifejezés +jelentése: egy kisbetűs `a`, amit egy kisbetűs `t`, amit egy `.` követ. És +ennek az egésznek a karakterlánc végén kell lennie. + ++"(at\.)" => The fat cat. sat. on the mat. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/y4Au4D/1) + ++"(at\.)$" => The fat cat. sat. on the mat. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/t0AkOd/1) + +## 3. Shorthand Karakter osztályok + +A gyakran használt karakter osztályokra a reguláris kifejezésnek vannak +rövidítései, amikkel kényelmesebben tudunk használni általános kifejezéseket. +A shorthand karakter osztályok a következők: + +|Rövidítés|Leírás| +|:----:|----| +|.|Minden karakter a sortörésen kívül.| +|\w|Az alfanumerikus karakterekre illeszkedik: `[a-zA-Z0-9_]`| +|\W|A nem alfanumerikus karakterekre illeszkedik: `[^\w]`| +|\d|Számra illeszkedik: `[0-9]`| +|\D|Nem számra illeszkedik: `[^\d]`| +|\s|Whitespace karakterre illeszkedik: `[\t\n\f\r\p{Z}]`| +|\S|Nem whitespace karakterre illeszkedik: `[^\s]`| + +## 4. Lookaround + +A lookbehind (hátranézés) és a lookahead (előrenézés) speciális típusai a +***nem tárolt csoport*** oknak, amiket illeszkedésre használnak, de nincsenek +benne az illeszkedési listában. Az előrenézést akkor használjuk, ha feltételezzük, +hogy ezt a mintát egy másik minta előzi meg, vagy követi. Például kell nekünk +az összes szám ami előtt `$` karakter áll a következő karakterláncból: `$4.44 and $10.88`. +Ezt a mintát fogjuk használni: `(?<=\$)[0-9\.]*`, aminek a jelentése: Szedd ki az +összes számot ami `.` karaktert tartalmaz és megelőzi egy `$` karakter. A +következő lookaround-okat használhatjuk: + +|Szimbólum|Leírás| +|:----:|----| +|?=|Positive Lookahead| +|?!|Negative Lookahead| +|?<=|Positive Lookbehind| +|? +"(T|t)he(?=\sfat)" => The fat cat sat on the mat. ++"(T|t)he(?!\sfat)" => The fat cat sat on the mat. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/V32Npg/1) + +### 4.3 Positive Lookbehind + +A pozitív hátranézést akkor használjuk, ha kell az összes illeszkedés, amit +egy megadott minta előz meg. A pozitív hátranézés így van jelölve: `(?<=...)`. +A `(?<=(T|t)he\s)(fat|mat)` jelentése: szedd ki az összes `fat` vagy `mat` szót +amelyek a `The` vagy a `the` szavak után vannak. + ++"(?<=(T|t)he\s)(fat|mat)" => The fat cat sat on the mat. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/avH165/1) + +### 4.4 Negative Lookbehind + +A negatív hátranézést akkor használjuk, ha kell az összes illeszkedés, amit nem +egy megadott minta előz meg. Jelölése: `(? +"(?<!(T|t)he\s)(cat)" => The cat sat on cat. ++"The" => The fat cat sat on the mat. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/dpQyf9/1) + ++"/The/gi" => The fat cat sat on the mat. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/ahfiuh/1) + +### 5.2 Globális keresés + +A `g` módosítót arra használjuk, hogy globálisan keressünk illeszkedéseket. +(Megkeresi az összes előfordulást, nem áll meg az első egyezés után). Például +a `/.(at)/g` kifejezés jelentése: minden karakter, kivéve a sortörést, amelyet +`a` és `t` követ. Mivel megadtuk a `g` flag-et, az összes ilyenre fog illeszkedni, +nem csak az elsőre (ami az alapértelmezett viselkedés). + ++"/.(at)/" => The fat cat sat on the mat. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/jnk6gM/1) + ++"/.(at)/g" => The fat cat sat on the mat. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/dO1nef/1) + +### 5.3 Többsoros + +Az `m` módosítót a többsoros illeszkedésekhez használjuk. Ahogy előzőleg beszéltük, +a horgonyokat `(^, $)` arra használjuk, hogy megnézzük, a minta az eleje, vagy a vége-e +a vizsgált karakterláncnak. De ha azt szeretnénk, hogy a horgonyok az összes soron +működjenek, használjuk az `m` módosítót. Például a `/at(.)?$/gm` kifejezés jelentése: +kisbetűs `a` karakter, amit egy kisbetűs `t` követ, amit opcionálisan bármi követhet, +kivéve sortörés. És az `m` flag miatt a reguláris kifejezés motor az összes sor +végéig keres illeszkedést. + ++"/.at(.)?$/" => The fat + cat sat + on the mat. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/hoGMkP/1) + ++"/.at(.)?$/gm" => The fat + cat sat + on the mat. ++ +[Teszteld a reguláris kifejezést](https://regex101.com/r/E88WE2/1) + +## Hozzájárulás + +* Jelents hibákat +* Nyiss pull request-eket fejlesztésekkel +* Hírdesd az igét +* Érj el közvetlenül itt: ziishaned@gmail.com vagy [](https://twitter.com/ziishaned) + +## Licenc + +MIT © [Zeeshan Ahmad](https://twitter.com/ziishaned) diff --git a/translations/README-id.md b/translations/README-id.md new file mode 100644 index 00000000..548aec16 --- /dev/null +++ b/translations/README-id.md @@ -0,0 +1,604 @@ ++
+ +## Terjemahan: + +* [English](README.md) +* [German](translations/README-de.md) +* [Español](translations/README-es.md) +* [Français](translations/README-fr.md) +* [Português do Brasil](translations/README-pt_BR.md) +* [中文版](translations/README-cn.md) +* [日本語](translations/README-ja.md) +* [한국어](translations/README-ko.md) +* [Turkish](translations/README-tr.md) +* [Greek](translations/README-gr.md) +* [Magyar](translations/README-hu.md) +* [Polish](translations/README-pl.md) +* [Русский](translations/README-ru.md) +* [Tiếng Việt](translations/README-vn.md) +* [Bahasa Indonesia](translations/README-id.md) +* [فارسی](translations/README-fa.md) +* [עברית](translations/README-he.md) + + +## Apa itu Ekspresi Reguler? + +
+ ++ +
+ +
+ +> Ekspresi reguler adalah sekelompok karakter atau simbol yang digunakan untuk menemukan pola tertentu dalam sebuah teks. + +Ekspresi reguler adalah pola yang dicocokkan dengan string subjek dari +kiri ke kanan. Ekspresi reguler digunakan untuk mengganti teks dalam string, +memvalidasi formulir, mengekstrak substring dari string berdasarkan kecocokan pola, +dan masih banyak lagi. Istilah "ekspresi reguler" adalah suap, jadi kamu biasanya akan +temukan istilah yang disingkat "regex" atau "regexp". + +Bayangkan Anda sedang menulis aplikasi dan Anda ingin menetapkan aturan kapan a +pengguna memilih nama pengguna mereka. Kami ingin mengizinkan nama pengguna berisi huruf, +angka, garis bawah, dan tanda hubung. Kami juga ingin membatasi jumlah karakter +di username agar tidak terlihat jelek. Kita dapat menggunakan ekspresi reguler berikut untuk +memvalidasi nama pengguna: + ++ +
++
+ +Ekspresi reguler di atas dapat menerima string `john_doe`, `jo-hn_doe` dan +`john12_as`. Itu tidak cocok dengan `Jo` karena string itu berisi huruf besar +surat dan juga terlalu pendek. + +## Table of Contents + +- [Pencocokan Dasar](#1-basic-matchers) +- [Karakter Meta](#2-meta-characters) + - [Perhentian Penuh](#21-the-full-stop) + - [Set Karakter](#22-character-sets) + - [Set Karakter yang Dinegasikan](#221-negated-character-sets) + - [Pengulangan](#23-repetitions) + - [Tanda Bintang](#231-the-star) + - [Tanda Tambah](#232-the-plus) + - [Tanda Tanya](#233-the-question-mark) + - [Kurung Kurawal](#24-braces) + - [Menangkap Grup](#25-capturing-groups) + - [Grup yang Tidak Menangkap](#251-non-capturing-groups) + - [Alternasi](#26-alternation) + - [Karakter Spesial](#27-escaping-special-characters) + - [Anchor Text](#28-anchors) + - [Tanda Sisipan](#281-the-caret) + - [Tanda Dollar](#282-the-dollar-sign) +- [Set Karakter Singkatan](#3-shorthand-character-sets) +- [Melihat](#4-lookarounds) + - [Pandangan ke Depan Positif](#41-positive-lookahead) + - [Pandangan ke Depan Negatif](#42-negative-lookahead) + - [Pandangan Positif ke Belakang](#43-positive-lookbehind) + - [Pandangan negatif ke belakang](#44-negative-lookbehind) +- [Bendera](#5-flags) + - [Tidak peka huruf besar/kecil](#51-case-insensitive) + - [Pencarian Global](#52-global-search) + - [Multiline](#53-multiline) +- [Greedy vs Lazy Matching](#6-greedy-vs-lazy-matching) + +## 1. Pencocokan Dasar + +Ekspresi reguler hanyalah pola karakter yang kita gunakan untuk melakukan +pencarian dalam sebuah teks. Misalnya, ekspresi reguler `the` berarti: huruf +`t`, diikuti huruf `h`, diikuti huruf `e`. + ++
+"the" => The fat cat sat on the mat. ++ +[Uji ekspresi reguler](https://regex101.com/r/dmRygT/1) + +Ekspresi reguler `123` cocok dengan string `123`. Ekspresi reguler adalah +dicocokkan dengan string input dengan membandingkan setiap karakter di reguler +ekspresi ke setiap karakter dalam string input, satu demi satu. Reguler +ekspresi biasanya peka huruf besar/kecil sehingga ekspresi reguler `The` akan +tidak cocok dengan string `the`. + ++"The" => The fat cat sat on the mat. ++ +[Uji ekspresi reguler](https://regex101.com/r/1paXsy/1) + +## 2. Karakter Meta + +Karakter meta adalah blok bangunan ekspresi reguler. Meta +karakter tidak berdiri sendiri tetapi sebaliknya ditafsirkan dalam beberapa +cara spesial. Beberapa karakter meta memiliki arti khusus dan tertulis di dalamnya +tanda kurung siku. Karakter metanya adalah sebagai berikut: + +|Meta karakter|Deskripsi| +|:----:|----| +|.|Titik cocok dengan karakter tunggal apa pun kecuali jeda baris.| +|[ ]|Kelas karakter. Mencocokkan karakter apa pun yang ada di antara tanda kurung siku.| +|[^ ]|Kelas karakter yang dinegasikan. Cocok dengan karakter apa pun yang tidak ada di antara tanda kurung siku| +|*|Mencocokkan dengan 0 atau lebih pengulangan dari simbol sebelumnya.| +|+|Mencocokkan 1 atau lebih pengulangan dari simbol sebelumnya.| +|?|Jadikan simbol sebelumnya opsional.| +|{n,m}|Kurung Kurawal. Mencocokkan setidaknya "n" tetapi tidak lebih dari "m" pengulangan simbol sebelumnya.| +|(xyz)|Kelompok karakter. Mencocokkan karakter xyz dalam urutan yang tepat.| +|||Alternasi. Mencocokkan dengan karakter sebelum atau karakter setelah simbol.| +|\|Meloloskan dari karakter berikutnya. Ini memungkinkan Anda untuk mencocokkan karakter yang dipesan[ ] ( ) { } . * + ? ^ $ \ |
| +|^|Mencocokkan dengan awal input.| +|$|Mencocokkan dengan akhir input.| + +## 2.1 Perhentian Penuh + +Tanda titik `.` adalah contoh paling sederhana dari karakter meta. Karakter meta `.` +cocok dengan karakter tunggal apa pun. Itu tidak akan cocok dengan karakter kembali atau baris baru. +Misalnya, ekspresi reguler `.ar` berarti: karakter apa pun, diikuti oleh +huruf `a`, diikuti dengan huruf `r`. + ++".ar" => The car parked in the garage. ++ +[Uji ekspresi reguler](https://regex101.com/r/xc9GkU/1) + +## 2.2 Set Karakter + +Kumpulan karakter juga disebut kelas karakter. Tanda kurung siku digunakan untuk +menentukan set karakter. Gunakan tanda hubung di dalam set karakter untuk menentukan +jangkauan karakter. Urutan rentang karakter di dalam tanda kurung siku +tidak masalah. Misalnya, ekspresi reguler `[Tt]he` berarti: huruf besar +`T` atau huruf kecil `t`, diikuti huruf `h`, diikuti huruf `e`. + ++"[Tt]he" => The car parked in the garage. ++ +[Uji ekspresi reguler](https://regex101.com/r/2ITLQ4/1) + +Sebuah periode di dalam set karakter, bagaimanapun, berarti periode literal. yang biasa +ekspresi `ar[.]` berarti: karakter huruf kecil `a`, diikuti dengan huruf `r`, +diikuti dengan karakter titik `.`. + ++"ar[.]" => A garage is a good place to park a car. ++ +[Uji ekspresi reguler](https://regex101.com/r/wL3xtE/1) + +### 2.2.1 Set Karakter yang Dinegasikan + +Secara umum, simbol tanda sisipan mewakili awal string, tetapi ketika itu +diketik setelah kurung siku pembuka itu meniadakan set karakter. Untuk +contoh, ekspresi reguler `[^c]ar` berarti: karakter apa pun kecuali `c`, +diikuti dengan karakter `a`, diikuti dengan huruf `r`. + ++"[^c]ar" => The car parked in the garage. ++ +[Uji ekspresi reguler](https://regex101.com/r/nNNlq3/1) + +## 2.3 Pengulangan + +Karakter meta `+`, `*` atau `?` digunakan untuk menentukan berapa kali a +subpola dapat terjadi. Karakter meta ini bertindak secara berbeda di berbagai +situasi. + +### 2.3.1 Tanda Bintang + +Simbol `*` cocok dengan nol atau lebih pengulangan dari pencocokan sebelumnya. Itu +ekspresi reguler `a*` berarti: nol atau lebih pengulangan dari huruf kecil sebelumnya +karakter `a`. Tetapi jika itu muncul setelah set karakter atau kelas maka ia menemukan +pengulangan seluruh set karakter. Misalnya, ekspresi reguler +`[a-z]*` artinya: sejumlah huruf kecil dalam satu baris. + ++"[a-z]*" => The car parked in the garage #21. ++ +[Uji ekspresi reguler](https://regex101.com/r/7m8me5/1) + +Simbol `*` dapat digunakan dengan karakter meta `.` untuk mencocokkan string apa pun dari +karakter `.*`. Simbol `*` dapat digunakan dengan karakter spasi putih `\s` +untuk mencocokkan string karakter spasi. Misalnya, ungkapan +`\s*cat\s*` artinya: nol spasi atau lebih, diikuti dengan huruf kecil `c`, +diikuti dengan huruf kecil `a`, diikuti dengan huruf kecil `t`, +diikuti oleh nol atau lebih spasi. + ++"\s*cat\s*" => The fat cat sat on the concatenation. ++ +[Uji ekspresi reguler](https://regex101.com/r/gGrwuz/1) + +### 2.3.2 Tanda Tambah + +Simbol `+` cocok dengan satu atau lebih pengulangan karakter sebelumnya. Untuk +contoh, ekspresi reguler `c.+t` berarti: huruf kecil `c`, diikuti oleh +setidaknya satu karakter, diikuti dengan huruf kecil `t`. Itu perlu +mengklarifikasi bahwa `t` adalah `t` terakhir dalam kalimat. + ++"c.+t" => The fat cat sat on the mat. ++ +[Uji ekspresi reguler](https://regex101.com/r/Dzf9Aa/1) + +### 2.3.3 Tanda Tanya + +Dalam ekspresi reguler, karakter meta `?` membuat karakter sebelumnya +opsional. Simbol ini cocok dengan nol atau satu contoh karakter sebelumnya. +Misalnya, ekspresi reguler `[T]?he` artinya: Huruf besar opsional +`T`, diikuti dengan huruf kecil `h`, diikuti dengan huruf kecil `e`. + ++"[T]he" => The car is parked in the garage. ++ +[Uji ekspresi reguler](https://regex101.com/r/cIg9zm/1) + ++"[T]?he" => The car is parked in the garage. ++ +[Uji ekspresi reguler](https://regex101.com/r/kPpO2x/1) + +## 2.4 Braces + +Dalam ekspresi reguler, kurung kurawal (juga disebut quantifier) digunakan untuk +tentukan berapa kali karakter atau sekelompok karakter dapat +ulang. Misalnya, ekspresi reguler `[0-9]{2,3}` berarti: Setidaknya cocok +2 digit, tetapi tidak lebih dari 3, mulai dari 0 hingga 9. + ++"[0-9]{2,3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Uji ekspresi reguler](https://regex101.com/r/juM86s/1) + +Kita bisa meninggalkan nomor kedua. Misalnya, ekspresi reguler +`[0-9]{2,}` berarti: Mencocokkan 2 digit atau lebih. Jika kita juga menghapus koma, +ekspresi reguler `[0-9]{3}` berarti: Sama persis dengan 3 digit. + ++"[0-9]{2,}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Uji ekspresi reguler](https://regex101.com/r/Gdy4w5/1) + ++"[0-9]{3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Test the regular expression](https://regex101.com/r/Sivu30/1) + +## 2.5 Menangkap Grup + +Grup penangkap adalah grup subpola yang ditulis di dalam tanda kurung +`(...)`. Seperti yang dibahas sebelumnya, dalam ekspresi reguler, jika kita menempatkan quantifier +setelah karakter maka akan mengulangi karakter sebelumnya. Tetapi jika kita menempatkan quantifier +setelah grup penangkap kemudian mengulangi seluruh grup penangkap. Sebagai contoh, +ekspresi reguler `(ab)*` cocok dengan nol atau lebih pengulangan karakter +"ab". Kita juga dapat menggunakan karakter meta `|` bergantian di dalam grup penangkap. +Misalnya, ekspresi reguler `(c|g|p)ar` berarti: huruf kecil `c`, +`g` atau `p`, diikuti oleh `a`, diikuti oleh `r`. + ++"(c|g|p)ar" => The car is parked in the garage. ++ +[Uji ekspresi reguler](https://regex101.com/r/tUxrBG/1) + +Perhatikan bahwa menangkap grup tidak hanya cocok, tetapi juga menangkap, karakter untuk digunakan dalam +bahasa induk. Bahasa induk bisa berupa Python atau JavaScript atau hampir semua +bahasa yang mengimplementasikan ekspresi reguler dalam definisi fungsi. + +### 2.5.1 Grup yang Tidak Menangkap + +Grup yang tidak menangkap adalah grup yang cocok dengan karakter tetapi +tidak menangkap kelompok. Grup yang tidak menangkap dilambangkan dengan `?` diikuti oleh `:` +dalam tanda kurung `(...)`. Misalnya, ekspresi reguler `(?:c|g|p)ar` mirip dengan +`(c|g|p)ar` karena cocok dengan karakter yang sama tetapi tidak akan membuat grup tangkapan. + ++"(?:c|g|p)ar" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/Rm7Me8/1) + +Grup yang tidak menangkap dapat berguna saat digunakan dalam fungsi temukan-dan-ganti atau +ketika dicampur dengan grup penangkap untuk menjaga gambaran umum saat memproduksi jenis keluaran lainnya. +Lihat juga [4. Melihat-lihat](#4-lookaround). + +## 2.6 Alternasi + +Dalam ekspresi reguler, bilah vertikal `|` digunakan untuk mendefinisikan pergantian. +Pergantian seperti pernyataan OR antara beberapa ekspresi. Sekarang, Anda mungkin +berpikir bahwa set karakter dan pergantian bekerja dengan cara yang sama. Tapi yang besar +perbedaan antara set karakter dan pergantian adalah bahwa set karakter bekerja di +tingkat karakter tetapi pergantian bekerja pada tingkat ekspresi. Misalnya, +ekspresi reguler `(T|t)he|car` berarti: baik (huruf besar `T` atau huruf kecil +`t`, diikuti dengan huruf kecil `h`, diikuti dengan huruf kecil `e`) ATAU +(huruf kecil `c`, diikuti dengan huruf kecil `a`, diikuti oleh +huruf kecil `r`). Perhatikan bahwa saya menyertakan tanda kurung untuk kejelasan, untuk menunjukkan bahwa salah satu ekspresi +dalam tanda kurung dapat dipenuhi dan itu akan cocok. + ++"(T|t)he|car" => The car is parked in the garage. ++ +[Uji ekspresi reguler](https://regex101.com/r/fBXyX0/1) + +## 2.7 Karakter Spesial + +Garis miring terbalik `\` digunakan dalam ekspresi reguler untuk keluar dari karakter berikutnya. Ini +memungkinkan kita untuk menyertakan karakter yang dicadangkan seperti `{ } [ ] / \ + * . $ ^ | ?` sebagai karakter yang cocok. Untuk menggunakan salah satu karakter khusus ini sebagai karakter yang cocok, awali dengan `\`. + +Misalnya, ekspresi reguler `.` digunakan untuk mencocokkan karakter apa pun kecuali a +garis baru. Sekarang, untuk mencocokkan `.` dalam string input, ekspresi reguler +`(f|c|m)at\.?` artinya: huruf kecil `f`, `c` atau `m`, diikuti dengan huruf kecil +`a`, diikuti dengan huruf kecil `t`, diikuti dengan `.` . opsional +karakter. + ++"(f|c|m)at\.?" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/DOc5Nu/1) + +## 2.8 Anchor Text + +Dalam ekspresi reguler, kami menggunakan jangkar untuk memeriksa apakah simbol yang cocok adalah +simbol awal atau simbol akhir dari string input. Jangkar terdiri dari dua jenis: +Tipe pertama adalah tanda sisipan `^` yang memeriksa apakah karakter yang cocok adalah yang pertama +karakter input dan tipe kedua adalah tanda dolar `$` yang memeriksa apakah cocok +karakter adalah karakter terakhir dari string input. + +### 2.8.1 Tanda Sisipan + +Simbol tanda sisipan `^` digunakan untuk memeriksa apakah karakter yang cocok adalah karakter pertama +dari string masukan. Jika kita menerapkan ekspresi reguler berikut `^a` (artinya 'a' harus +karakter awal) ke string `abc`, itu akan cocok dengan `a`. Tapi jika kita melamar +ekspresi reguler `^b` ke string di atas, itu tidak akan cocok dengan apa pun. +Karena dalam string `abc`, "b" bukanlah karakter awal. Mari lihat +di ekspresi reguler lain `^(T|t)he` yang artinya: huruf besar `T` atau +huruf kecil `t` harus menjadi karakter pertama dalam string, diikuti oleh a +huruf kecil `h`, diikuti dengan huruf kecil `e`. + ++"(T|t)he" => The car is parked in the garage. ++ +[Uji ekspresi reguler](https://regex101.com/r/5ljjgB/1) + ++"^(T|t)he" => The car is parked in the garage. ++ +[Uji ekspresi reguler](https://regex101.com/r/jXrKne/1) + +### 2.8.2 Tanda Dolar + +Tanda dolar `$` digunakan untuk memeriksa apakah karakter yang cocok adalah karakter terakhir +dalam tali. Misalnya, ekspresi reguler `(at\.)$` berarti: a +huruf kecil `a`, diikuti dengan huruf kecil `t`, diikuti oleh `.` +karakter dan matcher harus berada di akhir string. + ++"(at\.)" => The fat cat. sat. on the mat. ++ +[Uji ekspresi reguler](https://regex101.com/r/y4Au4D/1) + ++"(at\.)$" => The fat cat. sat. on the mat. ++ +[Uji ekspresi reguler](https://regex101.com/r/t0AkOd/1) + +## 3. Set Karakter Singkatan + +Ada sejumlah singkatan yang mudah digunakan untuk set karakter yang umum digunakan/ +ekspresi reguler: + +|Singkatan|Deskripsi| +|:----:|----| +|.|Karakter apa pun kecuali baris baru| +|\w|Mencocokkan karakter alfanumerik: `[a-zA-Z0-9_]`| +|\W|Mencocokkan karakter non-alfanumerik: `[^\w]`| +|\d|Mencocokkan digit: `[0-9]`| +|\D|Mencocokkan non-digit: `[^\d]`| +|\s|Mencocokkan karakter spasi putih: `[\t\n\f\r\p{Z}]`| +|\S|Mencocokkan karakter non-spasi: `[^\s]`| + +## 4. Melihat-lihat + +Melihat ke belakang dan melihat ke depan (juga disebut melihat sekeliling) adalah jenis tertentu dari +***grup non-penangkapan*** (digunakan untuk mencocokkan pola tetapi tanpa menyertakannya dalam pencocokan +daftar). Lookarounds digunakan ketika sebuah pola harus +didahului atau diikuti oleh pola lain. Misalnya, bayangkan kita ingin mendapatkan semua +angka yang didahului oleh karakter `$` dari string +`$4,44 dan $10,88`. Kami akan menggunakan ekspresi reguler berikut `(?<=\$)[0-9\.]*` +yang artinya: dapatkan semua angka yang mengandung karakter `.` dan didahului +oleh karakter `$`. Ini adalah lookaround yang biasa digunakan +ekspresi: + +|Simbol|Deskripsi| +|:----:|----| +|?=|Pandangan ke Depan Positif| +|?!|Melihat ke Depan Negatif| +|?<=|Tampilan Positif di Belakang| +|? +"(T|t)he(?=\sfat)" => The fat cat sat on the mat. ++"(T|t)he(?!\sfat)" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/V32Npg/1) + +### 4.3 Pandangan Positif ke Belakang + +Positif melihat ke belakang digunakan untuk mendapatkan semua kecocokan yang didahului oleh a +pola tertentu. Positif lookbehinds ditulis `(?<=...)`. Misalnya, +ekspresi reguler `(?<=(T|t)he\s)(fat|mat)` artinya: dapatkan semua kata `fat` atau `mat` +dari string input yang datang setelah kata `The` atau `the`. + ++"(?<=(T|t)he\s)(fat|mat)" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/avH165/1) + +### 4.4 Pandangan negatif ke belakang + +Pandangan belakang negatif digunakan untuk mendapatkan semua kecocokan yang tidak didahului oleh a +pola tertentu. Tampilan negatif di belakang ditulis `(? +"(?<!(T|t)he\s)(cat)" => The cat sat on cat. ++"The" => The fat cat sat on the mat. ++ +[Uji ekspresi reguler](https://regex101.com/r/dpQyf9/1) + ++"/The/gi" => The fat cat sat on the mat. ++ +[Uji ekspresi reguler](https://regex101.com/r/ahfiuh/1) + +### 5.2 Pencarian Global + +Pengubah `g` digunakan untuk melakukan kecocokan global (menemukan semua kecocokan daripada +berhenti setelah pertandingan pertama). Misalnya, ekspresi reguler`/.(at)/g` +berarti: karakter apa pun kecuali baris baru, diikuti dengan huruf kecil `a`, +diikuti dengan huruf kecil `t`. Karena kami menyediakan flag `g` di akhir +ekspresi reguler, sekarang akan menemukan semua kecocokan dalam string input, bukan hanya yang pertama (yang merupakan perilaku default). + ++"/.(at)/" => The fat cat sat on the mat. ++ +[Uji ekspresi reguler](https://regex101.com/r/jnk6gM/1) + ++"/.(at)/g" => The fat cat sat on the mat. ++ +[Uji ekspresi reguler](https://regex101.com/r/dO1nef/1) + +### 5.3 Multiline + +Pengubah `m` digunakan untuk melakukan pencocokan multi-baris. Seperti yang telah kita bahas sebelumnya, +jangkar `(^, $)` digunakan untuk memeriksa apakah suatu pola ada di awal input atau +tamat. Tetapi jika kita ingin jangkar bekerja pada setiap baris, kita menggunakan +bendera `m`. Misalnya, ekspresi reguler `/at(.)?$/gm` berarti: huruf kecil +`a`, diikuti dengan huruf kecil `t` dan, opsional, apa pun kecuali +baris baru. Dan karena flag `m`, mesin ekspresi reguler sekarang cocok dengan pola +di akhir setiap baris dalam sebuah string. + ++"/.at(.)?$/" => The fat + cat sat + on the mat. ++ +[Uji ekspresi reguler](https://regex101.com/r/hoGMkP/1) + ++"/.at(.)?$/gm" => The fat + cat sat + on the mat. ++ +[Uji ekspresi reguler](https://regex101.com/r/E88WE2/1) + +## 6. Greedy vs Lazy Matching +Secara default, regex akan melakukan kecocokan greedy, yang berarti kecocokan akan berlangsung selama +mungkin. Kita dapat menggunakan `?` untuk mencocokkan dengan cara yang lazy, yang berarti pencocokan harus sesingkat mungkin. + ++"/(.*at)/" => The fat cat sat on the mat.+ + +[Uji ekspresi reguler](https://regex101.com/r/AyAdgJ/1) + ++"/(.*?at)/" => The fat cat sat on the mat.+ + +[Uji ekspresi reguler](https://regex101.com/r/AyAdgJ/2) + + +## Kontribusi + +* Buka pull request dengan peningkatan +* Diskusikan ide dalam issue +* Sebarkan materinya +* Jangkau dengan umpan balik apa pun [](https://twitter.com/ziishaned) + +## Lisensi + +MIT © [Zeeshan Ahmad](https://twitter.com/ziishaned) diff --git a/translations/README-it.md b/translations/README-it.md new file mode 100644 index 00000000..1d4a3021 --- /dev/null +++ b/translations/README-it.md @@ -0,0 +1,477 @@ ++
+ + +## Translations: + +* [English](README.md) +* [German](translations/README-de.md) +* [Español](translations/README-es.md) +* [Français](translations/README-fr.md) +* [Português do Brasil](translations/README-pt_BR.md) +* [中文版](translations/README-cn.md) +* [日本語](translations/README-ja.md) +* [한국어](translations/README-ko.md) +* [Turkish](translations/README-tr.md) +* [Greek](translations/README-gr.md) +* [Magyar](translations/README-hu.md) +* [Polish](translations/README-pl.md) +* [Русский](translations/README-ru.md) +* [Tiếng Việt](translations/README-vn.md) +* [فارسی](translations/README-fa.md) +* [עברית](translations/README-he.md) + + +## Cosa sono le Espressioni Regolari? + +
+ ++ +
+ +
+ +> Un'espressione regolare è un insieme di caratteri e simboli utilizzati per trovare una specifica sequenza (pattern) di testo. + + +Un'espressione regolare è una sequenza che corrisponde a una stringa di testo letta da sinistra a destra. Le espressioni regolari sono utilizzate per sostituire parti di testo in una stringa, validare moduli, estrarre parti di stringhe basate sulla corrispondenza di uno schema e molto altro. Il termine "Espressione regolare" è molto lungo quindi è normalmente abbreviato con "regex" o "regexp". + +Immagina che stai scrivendo un applicazione e hai bisogno di impostare una regola per quando un utente sceglie il suo nome utente. Vogliamo consentire che il nome utente contenga lettere, numeri, carattere di sottolineo e il trattino, vogliamo inoltre limitare il numero di caratteri del nome utente. Possiamo utilizzare la seguente espressione regolare per validare il nome utente: ++ +
++
+ +L'espressione regolare riportata sopra può accettare le stringhe `john_doe`, `jo-hn_doe` e `john12_as`. Non c'è corrispondenza con `Jo` perché contiene una lettera maiuscola ed inoltre è troppo breve. + +## Sommario + +- [Corrispondenze di base](#1-basic-matchers) +- [Caratteri jolly](#2-meta-characters) + - [Il punto](#21-the-full-stop) + - [Classe di caratteri](#22-character-sets) + - [Negazione di classe di carattere](#221-negated-character-sets) + - [Ripetizioni](#23-repetitions) + - [Simbolo Asterisco](#231-the-star) + - [Simbolo Più](#232-the-plus) + - [Carattere Punto di Domanda](#233-the-question-mark) + - [Parentesi](#24-braces) + - [Raggruppamento e cattura di caratteri](#25-capturing-groups) + - [Raggruppamento di caratteri senza cattura](#251-non-capturing-groups) + - [Alternativa](#26-alternation) + - [Carattere speciale Escape](#27-escaping-special-characters) + - [Ancore](#28-anchors) + - [Segno di omissione ^](#281-the-caret) + - [Il simbolo del dollaro](#282-the-dollar-sign) +- [Classe di caratteri rapide](#3-shorthand-character-sets) +- [Guardarsi intorno](#4-lookarounds) + - [Lookahead positivo](#41-positive-lookahead) + - [Lookahead negativo](#42-negative-lookahead) + - [Lookbehind positivo](#43-positive-lookbehind) + - [Lookbehind negativo](#44-negative-lookbehind) +- [Opzioni](#5-flags) + - [Sensibilità ai caratteri maiuscoli e minuscoli](#51-case-insensitive) + - [Ricerca globale](#52-global-search) + - [Riga multipla](#53-multiline) +- [Corrispondenza vorace vs pigra](#6-greedy-vs-lazy-matching) + +## 1. Corrispondenze di base + +Un'espressione regolare non è altro che una sequenza di caratteri usati per eseguire ricerche in un testo. Ad esempio, l'espressione regolare `the` corrisponde a: la lettera `t`, seguita dalla lettera `h`, seguita dalla lettera `e`. + ++
+"the" => The fat cat sat on the mat. ++ +[Verifica l'espressione regolare](https://regex101.com/r/dmRygT/1) + +L'espressione regolare `123` corrisponde alla stringa `123`. L'espressione regolare viene confrontata con il testo da ricercare carattere per carattere, al fine di trovare la corrispondenza completa. +Le espressioni regolari sono normalmente sensibili a caratteri maiuscoli e minuscoli, perciò l'espressione regolare `The` non troverà corrispondenza con il testo `the`. + ++"The" => The fat cat sat on the mat. ++ +[Verifica l'espressione regolare](https://regex101.com/r/1paXsy/1) + +## 2. Caratteri jolly + +I caratteri jolly sono i mattoncini per la costruzione di espressioni regolari. I caratteri jolly non vengono usati letteralmente, vengono invece interpretati come caratteri speciali. Alcuni caratteri jolly hanno un significato speciale se inseriti all'interno di parentesi quadre. I caratteri jolly sono i seguenti: + +|Carattere jolly|Descrizione| +|:----:|----| +|.|Il punto corrisponde ad ogni carattere eccetto l'invio e l'interruzione di riga.| +|[ ]|Classe di caratteri. Corrispondenza con ciascun carattere contenuto tra le parentesi.| +|[^ ]|Negazione di classe di caratteri. Corrispondenza con ciascun carattere non contenuto all'interno delle parentesi| +|*|Corrispondenza con zero o più ripetizioni del carattere che lo precede.| +|+|Corrispondenza con una o più ripetizioni del carattere che lo precede| +|?|Rende opzionale il carattere che lo precede.| +|{n,m}|Parentesi graffe. Corrisponde con le ripetizione minima di "n" ma non più di "m", del carattere che le precede.| +|(xyz)|Gruppo di caratteri. Corrispondenza con i caratteri tra parentesi xyz solo nell'ordine esatto.| +|||Alternativa. Corrispondenza con il carattere che precede o con quello che segue.| +|\|Escape sul carattere successivo. Consente la corrispondenza con i caratteri riservati[ ] ( ) { } . * + ? ^ $ \ |
| +|^|Corrispondenza con l'inizio del testo.| +|$|Corrispondenza con la fine del testo.| + +## 2.1 Il punto + +Il punto `.` è il più semplice esempio di carattere jolly. Il carattere jolly `.` ha corrispondenza con ogni singolo carattere nel testo da cercare. Non ha corrispondenza con i caratteri di invio e fine riga. +Ad esempio, l'espressione regolare `.ar` significa: ciascun carattere, seguito dalla lettera `a`, seguita dalla lettera `r`. + ++".ar" => The car parked in the garage. ++ +[Verifica l'espressione regolare](https://regex101.com/r/xc9GkU/1) + +## 2.2 Classi di carattere + +Le parentesi quadre sono utilizzate per definire una classe di caratteri. Si può utilizzare il trattino per definire degli intervalli all'interno della classe. L'ordine dei caratteri utilizzati nella classe non ha influenza sul risultato. Ad esempio, l'espressione regolare `[Tt]he` significa: una lettera maiuscola `T` o una lettera minuscola `t`, seguita dalla lettera `h`, seguita dalla lettera `e`. + ++"[Tt]he" => The car parked in the garage. ++ +[Verifica l'espressione regolare](https://regex101.com/r/2ITLQ4/1) + +Un punto all'interno di una classe di caratteri, in ogni caso, corrisponde al punto letterale. L'espressione regolare `ar[.]` corrisponde a: una lettera minuscola `a`, seguita dalla lettera `r`, seguita dal carattere `.`. + ++"ar[.]" => A garage is a good place to park a car. ++ +[Verifica l'espressione regolare](https://regex101.com/r/wL3xtE/1) + +### 2.2.1 Negazione di classe di carattere + +In generale, il carattere di omissione ^ rappresenta l'inizio di un testo, ma se inserito come primo carattere all'interno di parentesi quadre, funziona come negazione della classe di caratteri. Ad esempio, l'espressione regolare `[^c]ar` corrisponde a: qualsiasi carattere tranne la lettera `c`, seguito dalla lettera `a`, seguita dalla lettera `r`. + ++"[^c]ar" => The car parked in the garage. ++ +[Verifica l'espressione regolare](https://regex101.com/r/nNNlq3/1) + +## 2.3 Ripetizioni + +I caratteri jolly `+`, `*` o `?` sono utilizzati per specificare quante volte uno schema si può ripetere. Questi caratteri jolly agiscono in modo differente per differenti situazioni. + +### 2.3.1 Simbolo Asterisco + +Il simbolo `*` corrisponde a zero o più ripetizioni della sequenza precedente. L'espressione regolare `a*` corrisponde a: zero o più ripetizioni della precedente lettera minuscola `a`. +Se il simbolo viene utilizzato a seguito di una classe di caratteri allora verranno applicate le ripetizioni all'intera classe. Ad esempio, l'espressione regolare `[a-z]*` corrisponde a: qualsiasi ripetizione di ciascuna lettera minuscola in un testo. + ++"[a-z]*" => The car parked in the garage #21. ++ +[Verifica l'espressione regolare](https://regex101.com/r/7m8me5/1) + +Il simbolo `*` più essere applicato al carattere jolly `.` per la corrispondenza con qualsiasi numero di caratteri `.*`. Il simbolo `*` può essere usato con lo spazio vuoto `\s` per la corrispondenza con una stringa di spazi vuoti. Ad esempio l'espressione regolare `\s*cat\s*` corrisponde a: nessuno o più spazi, seguiti dalla lettera minuscola `c`, seguita dalla lettera minuscola `a`, seguita dalla lettera minuscola `t`, seguite da nessuno o più spazi vuoti. + ++"\s*cat\s*" => The fat cat sat on the concatenation. ++ +[Verifica l'espressione regolare](https://regex101.com/r/gGrwuz/1) + +### 2.3.2 Simbolo Più + +Il simbolo `+` corrisponde a una o più ripetizioni della sequenza precedente. Ad esempio, l'espressione regolare `c.+t` corrisponde a: una lettera minuscola `c`, seguita da almeno un carattere, seguito dalla lettera minuscola `t`. +È importante chiarire che `t` corrisponde all'ultima lettera `t` nella stringa. + ++"c.+t" => The fat cat sat on the mat. ++ +[Verifica l'espressione regolare](https://regex101.com/r/Dzf9Aa/1) + +### 2.3.3 Carattere Punto di Domanda + +Nelle espressioni regolari, il carattere jolly `?` rende opzionale il carattere che lo precede. Questo simbolo corrisponde alla ripetizione zero o una volta della sequenza che lo precede. +Ad esempio, l'espressione regolare `[T]?he` corrisponde a: Lettera maiuscola opzionale `T`, seguita, se presente, dalla lettera maiuscola `h`, seguita dalla lettera minuscola `e`. + ++"[T]he" => The car is parked in the garage. ++ +[Verifica l'espressione regolare](https://regex101.com/r/cIg9zm/1) + ++"[T]?he" => The car is parked in the garage. ++ +[Verifica l'espressione regolare](https://regex101.com/r/kPpO2x/1) + +## 2.4 Parentesi graffe + +Nelle espressioni regolari, le parentesi graffe (chiamate anche quantificatori) sono utilizzate per specificare il numero di volte che un carattere o una classe di caratteri possono essere ripetute per mantenere la corrispondenza. Ad esempio, l'espressione regolare `[0-9]{2,3}` corrisponde a: Almeno 2 cifre, ma non più di 3, nell'intervallo da 0 a 9. + ++"[0-9]{2,3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Verifica l'espressione regolare](https://regex101.com/r/juM86s/1) + +Si può omettere il secondo numero. Ad esempio, l'espressione regolare `[0-9]{2,}` corrisponde a: 2 o più cifre. Inoltre possiamo rimuove la virgola di separazione, l'espressione regolare `[0-9]{3}` corrisponde a: esattamente 3 cifre. + ++"[0-9]{2,}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Verifica l'espressione regolare](https://regex101.com/r/Gdy4w5/1) + ++"[0-9]{3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Verifica l'espressione regolare](https://regex101.com/r/Sivu30/1) + +## 2.5 Raggruppamento e cattura di caratteri + +Un gruppo di caratteri è un sottoschema scritto all'interno di parentesi `(...)`. Come esposto in precedenza, se inseriamo un quantificatore a seguito di un carattere, viene definita la ripetizione del carattere stesso; allo stesso modo, se inseriamo un quantificatore a seguito di un gruppo di caratteri, definiamo la ripetizione dell'intero gruppo. Ad esempio, l'espressione regolare `(ab)*` corrisponde a zero o più ripetizioni della sequenza esatta di lettere minuscole "ab". +Si può inoltre utilizzare il carattere di alternativa `|` all'interno di un gruppo di caratteri. +Ad esempio, l'espressione regolare `(c|g|p)ar` corrisponde a: una lettera minuscola a scelta tra `c`, `g` o `p`, seguita dalla lettera minuscola `a`, seguite dalla lettera minuscola `r`. + ++"(c|g|p)ar" => The car is parked in the garage. ++ +[Verifica l'espressione regolare](https://regex101.com/r/tUxrBG/1) + +Nota che il gruppo di carattere non trova solo corrispondenza, ma cattura il contenuto del gruppo, per utilizzarlo in un linguaggio di programmazione. Il linguaggio può essere Python, Javascript o qualsiasi linguaggio che implementi funzioni per l'utilizzo di espressioni regolari. + +### 2.5.1 Raggruppamento di caratteri senza cattura + +Un gruppo di caratteri senza cattura è un gruppo utilizzato per la corrispondenza ma non per la cattura. È definito dal carattere `?` seguito da `:` all'interno delle parentesi `(...)`. Ad esempio, l'espressione regolare `(?:c|g|p)ar` è simile a `(c|g|p)ar`, corrisponde alla stessa stringa ma non cattura il gruppo. + ++"(?:c|g|p)ar" => The car is parked in the garage. ++ +[Verifica l'espressione regolare](https://regex101.com/r/Rm7Me8/1) + +I gruppi senza cattura sono utili per funzioni di ricerca e sostituzione o quando utilizzati in abbinata con gruppi di cattura per produrre diversi tipi di output. +Vedere anche [4. Guardarsi intorno](#4-lookaround). + +## 2.6 Alternativa + +In un'espressione regolare, la barra verticale `|` è utilizzata per definire alternative. +L'alternativa corrisponde alla dichiarazione OR tra espressioni multiple. Sagrai pensando che gli insiemi di caratteri e le alternative funzionino allo stesso modo, ma la grande differenza è che l'alternativa funziona a livello di espressione. Ad esempio, l'espressione regolare `(T|t)he|car` corrisponde a: sia (una lettera maiuscola `T` o una lettera minuscola `t`, seguita dalla lettera minuscola `h`, seguita da una lettera minuscola `e`), sia +(Una lettera minuscola `c`, seguita da una lettera minuscola `a`, seguita dalla lettera minuscola `r`). +Nota che sono state incluse le parentesi per chiarezza, per dimostrare come le espressioni possono funzionare anche all'interno delle parentesi stesse. + ++"(T|t)he|car" => The car is parked in the garage. ++ +[Verifica l'espressione regolare](https://regex101.com/r/fBXyX0/1) + +## 2.7 Carattere speciale Escape + +Il carattere di escape `\` è utilizzato nelle espressioni regolari per annullare la funzione del carattere jolly seguente. Questo consente di includere caratteri riservati, come `{ } [ ] / \ + * . $ ^ | ?` all'interno di un'espressione regolare per la corrispondenza letterale. + +Ad esempio, l'espressione regolare `.` è utilizzata per la corrispondenza con qualsiasi carattere eccetto il carattere di invio e di fine riga. Quindi, per la corrispondenza del carattere `.`, l'espressione regolare `(f|c|m)at\.?` corrisponde a: una lettera minuscola `f`, `c` o `m`, seguita dalla lettera minuscola `a`, seguita dalla lettera minuscola `t`, seguita dal carattere `.` opzionale. + ++"(f|c|m)at\.?" => The fat cat sat on the mat. ++ +[Verifica l'espressione regolare](https://regex101.com/r/DOc5Nu/1) + +## 2.8 Ancore + +Nelle espressioni regolari, si usano le ancore per la corrispondenza dell'espressione stessa, all'inizio o al termine di un testo. +Le ancora sono di due tipi: +Il primo tipo è il carattere di negazione `^` che verifica la corrispondenza all'inizio del testo, il secondo tipo è il carattere `$` che verifica la corrispondenza al termine del testo. + +### 2.8.1 Il carattere di negazione ^ + +Il simbolo di negazione `^` è usato per verificare la corrispondenza al primo carattere del testo. Utilizzando l'espressione regolare `^a` (significa che 'a' deve essere il primo carattere) con il testo `abc`, ci sarà corrispondenza con `a`. Applicando l'espressione regolare `^b` al testo precedente, non ci sarà alcuna corrispondenza. +Questo perché nel testo `abc`, la lettera "b" non è il carattere iniziale. Vediamo un'altra espressione regolare, `^(T|t)he` che corrisponde a: una lettera maiuscola `T` o una lettera minuscola `t` deve essere la prima lettera del testo, seguita dalla lettera minuscola `h`, seguita dalla lettera minuscola `e`. + ++"(T|t)he" => The car is parked in the garage. ++ +[Verifica l'espressione regolare](https://regex101.com/r/5ljjgB/1) + ++"^(T|t)he" => The car is parked in the garage. ++ +[Verifica l'espressione regolare](https://regex101.com/r/jXrKne/1) + +### 2.8.2 Il simbolo del Dollaro + +Il simbolo del collario `$` è utilizzato per verificare la corrispondenza con la parte finale del testo. Ad esempio, l'espressione regolare `(at\.)$` corrisponde a: una lettera minuscola `a`, seguita da una lettera minuscola `t`, seguita dal carattere punto `.`, il tutto deve trovarsi al termine del testo. + ++"(at\.)" => The fat cat. sat. on the mat. ++ +[Verifica l'espressione regolare](https://regex101.com/r/y4Au4D/1) + ++"(at\.)$" => The fat cat. sat. on the mat. ++ +[Verifica l'espressione regolare](https://regex101.com/r/t0AkOd/1) + +## 3. Classe di caratteri rapide + +Ci sono alcune classe di caratteri rapide per l'utilizzo nelle espressioni regolari: + +|Classe di caratteri rapide|Descrizione| +|:----:|----| +|.|Qualsiasi carattere tranne invio e fine riga| +|\w|Corrispondenza con caratteri alfanumerici: `[a-zA-Z0-9_]`| +|\W|Corrispondenza con caratteri non alfanumerici: `[^\w]`| +|\d|Corrispondenza con numeri: `[0-9]`| +|\D|Corrispondenza con caratteri che non siano numeri: `[^\d]`| +|\s|Corrispondenza con spazi vuoti: `[\t\n\f\r\p{Z}]`| +|\S|Corrispondenza con caratteri che non siano spazi vuoti: `[^\s]`| + +## 4. Guardarsi intorno + +Lookbehinds e lookaheads sono speciali tipi di ***gruppi di caratteri senza cattura***. Guardarsi intorno sono utilizzati quando uno schema deve essere preceduto o seguito da un altro schema. Ad esempio, pensiamo di dover selezionare i numeri preceduti dal carattere `$` nel testo `$4.44 and $10.88`. Useremo l'espressione regolare `(?<=\$)[0-9\.]*` che corrisponde a: selezionare tutti i numeri che contengono il carattere `.` e sono preceduti dal carattere `$`. Queste sono le espressioni di guardarsi intorno utilizzate: + +|Simbolo|Descrizione| +|:----:|----| +|?=|Lookahead positivo| +|?!|Lookahead negativo| +|?<=|Lookbehind positivo| +|? +"(T|t)he(?=\sfat)" => The fat cat sat on the mat. ++"(T|t)he(?!\sfat)" => The fat cat sat on the mat. ++ +[Verifica l'espressione regolare](https://regex101.com/r/V32Npg/1) + +### 4.3 Lookbehind positivo + +Lookbehind positivo è utilizzato per trovare il testo preceduto da uno specifico schema. Il lookbehind positivo è sxcritto come `(?<=...)`. Ad esempio, l'espressione regolare `(?<=(T|t)he\s)(fat|mat)` corrisponde a: tutte le parole `fat` o `mat` che seguono la parola `The` o `the`. + ++"(?<=(T|t)he\s)(fat|mat)" => The fat cat sat on the mat. ++ +[Verifica l'espressione regolare](https://regex101.com/r/avH165/1) + +### 4.4 Lookbehind negativo + +Lookbehind negativo è utilizzato per trovare il testo non preceduto da uno specifico schema. Il lookbehind negativo è sxcritto come `(? +"(?<!(T|t)he\s)(cat)" => The cat sat on cat. ++"The" => The fat cat sat on the mat. ++ +[Verifica l'espressione regolare](https://regex101.com/r/dpQyf9/1) + ++"/The/gi" => The fat cat sat on the mat. ++ +[Verifica l'espressione regolare](https://regex101.com/r/ahfiuh/1) + +### 5.2 Ricerca globale + +L'opzione `g` è utilizzata per estendere la ricerca a corrispondenze multiple. Ad esempio, l'espressione regolare `/.(at)/g` corrisponde a: qualsiasi carattere eccetto invio e nuova riga, seguito dalla lettera minuscola `a`, seguita dalla lettera minuscola `t`. L'utilizzo dell'opzione `g` estende la ricerca all'intero testo. + ++"/.(at)/" => The fat cat sat on the mat. ++ +[Verifica l'espressione regolare](https://regex101.com/r/jnk6gM/1) + ++"/.(at)/g" => The fat cat sat on the mat. ++ +[Verifica l'espressione regolare](https://regex101.com/r/dO1nef/1) + +### 5.3 Multi riga + +L'opzione `m` è utilizzata per estendere la corrispondenza in modalità multi riga. Come già esposto, le ancore `(^, $)` sono utilizzate per verificare se l'espressione si trova all'inizio o alla fine del testo. Volendo utilizzare le ancore su già righe di testo, si può attivare l'opzione `m`. Ad esempio, l'espressione regolare `/at(.)?$/gm` corrisponde a: una lettera minuscola `a`, seguita da una lettera minuscola `t` e, opzionalmente, qualsiasi carattere eccetto invio e nuova riga. Grazie all'opzione `m`, la corrispondenza viene estesa a ciascuna riga del testo. + ++"/.at(.)?$/" => The fat + cat sat + on the mat. ++ +[Verifica l'espressione regolare](https://regex101.com/r/hoGMkP/1) + ++"/.at(.)?$/gm" => The fat + cat sat + on the mat. ++ +[Verifica l'espressione regolare](https://regex101.com/r/E88WE2/1) + +## 6. Corrispondenza vorace vs pigra +Regex ha un funzionamento predefinito vorace, ,significa che la corrispondenza è più estesa possibile. Si può utilizzare `?` per determinare una corrispondenza più pigra, così la corrispondenza è più breve possibile. + ++"/(.*at)/" => The fat cat sat on the mat.+ + +[Verifica l'espressione regolare](https://regex101.com/r/AyAdgJ/1) + ++"/(.*?at)/" => The fat cat sat on the mat.+ + +[Verifica l'espressione regolare](https://regex101.com/r/AyAdgJ/2) + + +## Contribution + +* Open a pull request with improvements +* Discuss ideas in issues +* Spread the word +* Reach out with any feedback [](https://twitter.com/ziishaned) +* Traduzione italiana: Claudio Marconato (cmpro.it) + +## License + +MIT © [Zeeshan Ahmad](https://twitter.com/ziishaned) \ No newline at end of file diff --git a/README-ja.md b/translations/README-ja.md similarity index 90% rename from README-ja.md rename to translations/README-ja.md index 991a46e8..31c62402 100644 --- a/README-ja.md +++ b/translations/README-ja.md @@ -1,16 +1,43 @@ -
-
-
+
+ ++ +
+ + + ## 翻訳 -* [English](README.md) -* [中文版](README-cn.md) -* [日本語](README-ja.md) +* [English](../README.md) +* [German](../translations/README-de.md) +* [Español](../translations/README-es.md) +* [Français](../translations/README-fr.md) +* [Português do Brasil](../translations/README-pt_BR.md) +* [中文版](../translations/README-cn.md) +* [日本語](../translations/README-ja.md) +* [한국어](../translations/README-ko.md) +* [Turkish](../translations/README-tr.md) +* [Greek](../translations/README-gr.md) +* [Magyar](../translations/README-hu.md) +* [Polish](../translations/README-pl.md) +* [Русский](../translations/README-ru.md) +* [Tiếng Việt](../translations/README-vn.md) +* [فارسی](../translations/README-fa.md) +* [עברית](../translations/README-he.md) ## 正規表現とは +[](https://gum.co/learn-regex) + > 正規表現とは文中からある文字列のパターンを見つけるために使用される文字列や記号の組み合わせのことです。 正規表現とは対象の文字列に左から右にマッチするパターンのことを言います。 @@ -25,7 +52,7 @@
-
この正規表現によって `john_doe, jo-hn_doe, john12_as` などは許容されることになります。 @@ -188,7 +215,8 @@ シンボル `+` は直前の文字が 1 個以上続くパターンにマッチします。 例えば `c.+t` という正規表現は小文字の `c` の後に -任意の 1 文字が続き、さらに `t` が続くことを意味します。 +任意の 1 文字以上が続き、さらに `t` が続くことを意味します。 +この `t` は、その文における最後の `t` がマッチします。+
"c.+t" => The fat cat sat on the mat. @@ -216,6 +244,7 @@ [正規表現の動作確認をする](https://regex101.com/r/kPpO2x/1) ## 2.4 括弧 +この`t`は、その文における最後の`t`であることが明確である必要があります。 正規表現における括弧は数量子とも呼ばれますが、文字列がいくつ現れるかを示すために使用されます。 例えば、`[0-9]{2,3}` という正規表現は 2 桁以上 3 桁以下の数字 @@ -341,7 +370,7 @@ 正規表現ではよく使われる文字集合に対して短縮表記が提供されており、 便利なショートカットとして使用できます。 -省略表記には次のようなものがあります。 +短縮表記には次のようなものがあります。 |短縮表記|説明 | |:------:|-----------------------------------| @@ -355,7 +384,7 @@ ## 4. 前後参照 -しばしば前後参照とも呼ばれる先読みと後読みは **非キャプチャグループ** +先読みと後読み(前後参照とも呼ばれます)は **非キャプチャグループ** (パターンのマッチングはするがマッチングリストには含まれない)という 特殊な扱いがなされる機能です。 前後参照はあるパターンが別のあるパターンよりも先行または後続して現れることを示すために使用されます。 @@ -378,12 +407,12 @@ 肯定的な先読みを定義するには括弧を使用します。 その括弧の中で疑問符と等号を合わせて `(?=...)` のようにします。 先読みのパターンは括弧の中の等号の後に記述します。 -例えば `[T|t]he(?=\sfat)` という正規表現は小文字の `t` か大文字の `T` のどちらかの後に `h`, `e` が続きます。 +例えば `(T|t)he(?=\sfat)` という正規表現は小文字の `t` か大文字の `T` のどちらかの後に `h`, `e` が続きます。 括弧内で肯定的な先読みを定義していますが、これは `The` または `the` の後に `fat` が続くことを表しています。[正規表現の動作確認をする](https://regex101.com/r/8Efx5G/1) @@ -440,7 +469,7 @@ ### 5.1 大文字・小文字を区別しない -修飾子 `i` は大文字・小文字を区別しなくないときに使用します。 +修飾子 `i` は大文字・小文字を区別したくないときに使用します。 例えば `/The/gi` という正規表現は大文字の `T` の後に小文字の `h`, `e` が続くという意味ですが、 最後の `i` で大文字・小文字を区別しない設定にしています。 文字列内の全マッチ列を検索したいのでフラグ `g` も渡しています。 @@ -462,8 +491,8 @@ 修飾子 `g` はグローバル検索(最初のマッチ列を検索する代わりに全マッチ列を検索する)を 行うために使用します。 例えば `/.(at)/g` という正規表現は、改行を除く任意の文字列の後に -小文字の `a`, `t` が続きます。正規表現の最後にフラグ `g` を渡すことで -入力文字列内の全マッチ列を検索するようにしています。 +小文字の `a`, `t` が続きます。正規表現の最後にフラグ `g` を渡すことで、 +最初のマッチだけではなく(これがデフォルトの動作です)、入力文字列内の全マッチ列を検索するようにしています。-"[T|t]he(?=\sfat)" => The fat cat sat on the mat. +"(T|t)he(?=\sfat)" => The fat cat sat on the mat.[正規表現の動作確認をする](https://regex101.com/r/IDDARt/1) @@ -393,11 +422,11 @@ 否定的な先読みはあるパターンが後続しない全てのマッチング文字列を取得するために使用します。 否定的な先読みは肯定的な先読みと同じように定義しますが、 `=` の代わりに `!` を使うところが唯一の違いで、`(?!...)` と記述します。 -次の正規表現 `[T|t]he(?!\sfat)` について考えてみます。 +次の正規表現 `(T|t)he(?!\sfat)` について考えてみます。 これはスペースを挟んで `fat` が後続することがない全ての `The` または `the` を得ることができます。-"[T|t]he(?!\sfat)" => The fat cat sat on the mat. +"(T|t)he(?!\sfat)" => The fat cat sat on the mat.[正規表現の動作確認をする](https://regex101.com/r/V32Npg/1) @@ -406,11 +435,11 @@ 肯定的な後読みは特定のパターンが先行するような文字列を得るために使用します。 定義の仕方は `(?<=...)` とします。 -例えば `(?<=[T|t]he\s)(fat|mat)` という正規表現は +例えば `(?<=(T|t)he\s)(fat|mat)` という正規表現は `The` または `the` の後に続く全ての `fat` または `mat` が取得できます。-"(?<=[T|t]he\s)(fat|mat)" => The fat cat sat on the mat. +"(?<=(T|t)he\s)(fat|mat)" => The fat cat sat on the mat.[正規表現の動作確認をする](https://regex101.com/r/avH165/1) @@ -422,7 +451,7 @@ 例えば `(? -"(?<![T|t]he\s)(cat)" => The cat sat on cat. +"(?<!(T|t)he\s)(cat)" => The cat sat on cat."/.(at)/" => The fat cat sat on the mat. @@ -502,37 +531,13 @@ [正規表現の動作確認をする](https://regex101.com/r/E88WE2/1) -## おまけ - -* *正の整数*: `^\d+$` -* *負の整数*: `^-\d+$` -* *米国の電話番号*: `^+?[\d\s]{3,}$` -* *コード付きの米国の電話番号*: `^+?[\d\s]+(?[\d\s]{10,}$` -* *整数*: `^-?\d+$` -* *ユーザ名*: `^[\w.]{4,16}$` -* *英数字*: `^[a-zA-Z0-9]*$` -* *スペース込みの英数字*: `^[a-zA-Z0-9 ]*$` -* *パスワード*: `^(?=^.{6,}$)((?=.*[A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z]))^.*$` -* *Eメール*: `^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})*$` -* *IPv4 アドレス*: `^((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))*$` -* *小文字のみ*: `^([a-z])*$` -* *大文字のみ*: `^([A-Z])*$` -* *URL*: `^(((http|https|ftp):\/\/)?([[a-zA-Z0-9]\-\.])+(\.)([[a-zA-Z0-9]]){2,4}([[a-zA-Z0-9]\/+=%&_\.~?\-]*))*$` -* *VISA クレジットカード番号*: `^(4[0-9]{12}(?:[0-9]{3})?)*$` -* *日付 (DD/MM/YYYY)*: `^(0?[1-9]|[12][0-9]|3[01])[- /.](0?[1-9]|1[012])[- /.](19|20)?[0-9]{2}$` -* *日付 (MM/DD/YYYY)*: `^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2}$` -* *日付 (YYYY/MM/DD)*: `^(19|20)?[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])$` -* *MasterCard クレジットカード番号*: `^(5[1-5][0-9]{14})*$` -* *ハッシュタグ*: 前の文字列を含む (abc123#xyz456) または角括弧内にスペースを含む (#[foo bar]) : `\S*#(?:\[[^\]]+\]|\S+)` -* *@mentions*: `\B@[a-z0-9_-]+` - ## 貢献する -* 課題を発行する +* イシューを発行する * 修正をプルリクエストする * ドキュメントを普及させる * 作者に直接連絡を取る: ziishaned@gmail.com または [](https://twitter.com/ziishaned) ## ライセンス -MIT © [Zeeshan Ahmed](mailto:ziishaned@gmail.com) +MIT © [Zeeshan Ahmad](https://twitter.com/ziishaned) diff --git a/translations/README-ko.md b/translations/README-ko.md new file mode 100644 index 00000000..e34f3d25 --- /dev/null +++ b/translations/README-ko.md @@ -0,0 +1,464 @@ ++ +[Test the regular expression](https://regex101.com/r/IDDARt/1) + +### 4.2 부정형 전방탐색 + +부정형 전방탐색는 입력 문자열로부터 특정 패턴이 뒤에 나오지 않기를 바라는 상황에서 사용된다. 부정형 전방탐색는 우리가 긍정형 전방탐색를 정의하는 방식과 동일하게 정의된다. 하지만, 유일한 차이점은 등호 부호 `=` 대신 부정 부호 `!` 문자를 사용한다는 것이다, 즉 `(?!...)`. 정규 표현식 `[T|t]he(?!\sfat)`를 살펴보도록 하자. 이 정규 표현식은 공백 문자와 `fat` 문자열이 연속으로 나오지 않는 모든 `The` 혹은 `the` 문자열과 매치된다. + ++
+ + + +## 번역: + +* [English](../README.md) +* [German](../translations/README-de.md) +* [Español](../translations/README-es.md) +* [Français](../translations/README-fr.md) +* [Português do Brasil](../translations/README-pt_BR.md) +* [中文版](../translations/README-cn.md) +* [日本語](../translations/README-ja.md) +* [한국어](../translations/README-ko.md) +* [Turkish](../translations/README-tr.md) +* [Greek](../translations/README-gr.md) +* [Magyar](../translations/README-hu.md) +* [Polish](../translations/README-pl.md) +* [Русский](../translations/README-ru.md) +* [Tiếng Việt](../translations/README-vn.md) +* [فارسی](../translations/README-fa.md) +* [עברית](../translations/README-he.md) + +## 정규표현식이란 무엇인가? + +[](https://gum.co/learn-regex) + +> 정규표현식은 텍스트에서 특정 패턴을 찾아내는데 사용되는 문자 혹은 기호들의 집합이다. + +정규표현식(Regular expression)은 대상 문자열에 왼쪽에서 오른쪽 방향으로 매칭되는 하나의 패턴이다. "Regular expression"이라고 매번 발음하기 어렵기 때문에, 보통 약어로 "regex" 혹은 "regexp", "정규식"으로 축약되어 사용된다. 정규 표현식은 문자열 내부의 텍스트 대체, 포맷의 유효성 검사, 패턴 매칭을 기반으로한 문자열에서 일부 텍스트를 추출, 그리고 그 외에 다양한 목적을 위해 사용된다. + +당신이 하나의 어플리케이션을 작성하고 있고 사용자가 사용자명을 선택할 때 사용되는 규칙들을 정하고 싶다고 상상해보자. 예를 들어, 우리는 사용자명에 문자, 숫자, 밑줄 문자(\_), 그리고 하이픈이 포함되는 것은 허용하고 싶다. 또한, 사용자명의 글자수를 제한해서 사용자명이 지저분해보이지 않도록 하고 싶다. 이때 아래 정규표현식을 사용해 입력된 사용자명이 해당 규칙에 맞는지 검사할 수 있다. + +
+ ++ +
+
++
+ +위의 정규 표현식은 `john_doe`, `jo-hn_doe`, 그리고 `john12_as` 문자열을 받아들일 수 있다. `Jo`는 대문자를 포함하고 있고 길이가 너무 짧기 때문에 위의 정규표현식과 매칭되지 않는다. + + +## 목차 + +- [기본 매쳐](#1-기본-매쳐) +- [메타 문자](#2-메타-문자) + - [마침표](#21-마침표) + - [문자 집합](#22-문자-집합) + - [부정 문자 집합](#221-부정-문자-집합) + - [반복](#23-반복) + - [별 부호](#231-별-부호) + - [덧셈 부호](#232-덧셈-부호) + - [물음표](#233-물음표) + - [중괄호](#24-중괄호) + - [캡쳐링 그룹](#25-캡쳐-그룹) + - [논-캡쳐링 그룹](#251-논-캡쳐링-그룹) + - [대안 부호](#26-대안-부호) + - [특수 문자 이스케이핑](#27-특수-문자-이스케이핑) + - [앵커 부호](#28-앵커-부호) + - [캐럿 부호](#281-캐럿-부호) + - [달러 부호](#282-달러-부호) +- [단축형 문자열 집합](#3-단축형-문자열-집합) +- [전후방탐색](#4-전후방탐색) + - [긍정형 전방탐색](#41-긍정형-전방탐색) + - [부정형 전방탐색](#42-부정형-전방탐색) + - [긍정형 후방탐색](#43-긍정형-후방탐색) + - [부정형 후방탐색](#44-부정형-후방탐색) +- [플래그](#5-플래그) + - [대소문자 구분없음](#51-대소문자-구분없음) + - [전체 검색](#52-전체-검색) + - [멀티 라인](#53-멀티-라인) +- [탐욕적 vs 게으른 매칭](#6-탐욕적-vs-게으른-매칭) + +## 1. 기본 매쳐 + +하나의 정규 표현식은 단지 텍스트 내부의 검색을 수행하기 위한 문자열의 패턴이다. 예를 들어, 정규 표현식 `the`는 문자 `t` 다음에 문자 `h`, 그 다음에 문자 `e`가 나오는 것을 의미한다. + ++
+"the" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/dmRygT/1) + +정규 표현식 `123`은 문자열 `123`에 매칭된다. 정규 표현식은 정규 표현식의 각 문자(Character)와 입력된 문자열의 각 문자(Character)를 비교함으로써 해당 문자열과 매칭된다. 정규 표현식들은 일반적으로 대소문자를 구분하기 때문에, 정규 표현식 `The`는 문자열 `the`와 매칭되지 않는다. + ++"The" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/1paXsy/1) + +## 2. 메타 문자 + +메타 문자들은 정규 표현식의 빌딩 블락들이다. 메타 문자들은 자체적인 의미를 가지지 않고 특별한 방식으로 해석되어진다. 어떤 메타 문자열들은 특별한 의미를 가지며 대괄호안에서 쓰인다. 아래는 이러한 메타 문자열들이다: + +|메타 문자|설명| +|:----:| ----| +|.|온점(Period)는 줄바꿈을 제외한 어떤 종류의 단일 문자와 매치.| +|[ ]|문자 클래스. 대괄호 사이에 있는 문자들로 매치.| +|[^ ]|부정 문자 클래스. 대괄호 안에 포함되지 않은 모든 문자들로 매치.| +|\*|이 메타 문자의 바로 앞에 있는 심볼이 0번 이상 반복된 문자들과 매치.| +|+|이 메타 문자의 바로 앞에 있는 심볼이 한번 이상 반복된 문자들과 매치.| +|?|이 메타 문자의 바로 앞에 있는 심볼을 선택적(optional)으로 만듬.| +|{n,m}|중괄호. 이 메타 문자의 바로 앞에 위치한 심볼이 최소 n번 최대 m번의 반복된 문자들과 매치.| +|(xyz)|문자 그룹. 문자열 xyz와 정확히 같은 순서를 가진 문자들과 매치.| +|||대안. 문자가 이 메타 문자의 앞에 있는 심볼이거나 뒤에 있는 심볼이면 매치.| +|\|다음 문자 이스케이프(Escape). 예약된 문자열들[ ] ( ) { } . \* + ? ^ \$ \ |
을 이스케이핑함으로써 그 자체와 매칭되는 것을 허용.| +|^|입력의 시작과 매치.| +|\$|입력의 끝과 매치.| + +## 2.1 마침표 + +마침표(`.`)는 메타 문자의 가장 간단한 예다. 메타 문자 `.`는 어떠한 단일 문자와도 매치되지만 리턴 혹은 개행 문자와는 매치되지 않는다. 예를 들어, 정규 표현식 `.ar`은 어떠한 단일 문자 다음에 문자 `a`가 오고, 그 다음에 문자 `r`이 오는 패턴을 의미한다. + ++".ar" => The car parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/xc9GkU/1) + +## 2.2 문자 집합 + +문자 집합은 문자 클래스라고도 불린다. 대괄호는 이 문자 집합을 명시하기 위해 사용된다. 문자열 집합내에 사용된 하이픈은 문자들의 범위를 지정하는데 사용된다. 대괄호 내부에 명시된 문자들의 순서는 중요하지 않다. 예를 들어, 정규 표현식 `[Tt]he`는 대문자 `T` 혹은 소문자 `t`가 나온 다음에, 문자 `h`가 나오고 그 뒤에 문자 `e`가 나오는 패턴을 의미한다. + ++"[Tt]he" => The car parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/2ITLQ4/1) + +하지만, 문자 집합 내부에서 사용되는 온점(Period)은 온점 그 자체를 의미한다. 정규 표현식 `ar[.]`은 소문자 `a` 다음에 문자 `r`이 오고 그 뒤에 문자 `.`이 오는 패턴을 의미한다. + ++"ar[.]" => A garage is a good place to park a car. ++ +[Test the regular expression](https://regex101.com/r/wL3xtE/1) + +### 2.2.1 부정 문자 집합 + +일반적으로, 캐럿 기호(^)는 문자열의 시작지점을 나타내지만, 왼쪽 대괄호 바로 뒤에 위치했을때는 해당 문자 집합의 부정(negation)을 나타낸다. 예를 들어, 정규 표현식 `[^c]ar`은 문자 `c`를 제외한 어떠한 문자뒤에 문자 `a`가 오고, 그 뒤에 문자 `r`이 오는 패턴을 의미한다. + ++"[^c]ar" => The car parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/nNNlq3/1) + +## 2.3 반복 + +메타 문자 `+`, `*` 또는 `?`은 하위패턴(subpattern)이 몇 번 발생하는지 지정하는데 사용된다. 이러한 메타 문자들은 상황에 따라 다르게 동작한다. + +### 2.3.1 별 부호 + +`*` 부호는 부호 앞에 위치한 매처(matcher)가 0번 이상 반복된 문자열과 매치된다. 정규 표현식 `a*`은 소문자 `a`가 0번 이상 반복되는 패턴을 의미한다. 하지만, 만약 이 별 부호가 문자 집합(character set) 직후에 나오는 경우에는 문자 집합 전체의 반복을 찾게된다. 예를 들어, 정규 표현식 `[a-z]*`은 소문자들이 갯수와 상관없이 연속으로 반복되는 패턴을 의미한다. + ++"[a-z]*" => The car parked in the garage #21. ++ +[Test the regular expression](https://regex101.com/r/7m8me5/1) + +`*` 부호는 메타 문자 `.`와 함께 모든 문자열과 매치되는 패턴을 만드는데 사용될 수 있다. 또한, `*` 부호는 공백 문자 `\s`와 함께 공백 문자들로 이루어진 문자열과 매치되는 패턴을 만드는데 사용될 수 있다. 예를 들어, 정규 표현식 `\s*cat\s*`는 0번 이상 공백문자가 나온 이후에 소문자 `c`, 소문자 `a`, 소문자 `t`가 자체로 나오고 그 뒤에 다시 0번 이상의 공백문자가 나오는 패턴을 의미한다. + ++"\s*cat\s*" => The fat cat sat on the concatenation. ++ +[Test the regular expression](https://regex101.com/r/gGrwuz/1) + +### 2.3.2 덧셈 부호 + +`+` 부호는 부호 앞에 위치한 문자가 한번 이상 반복되는 패턴을 만드는데 사용된다. 예를 들어, 정규 표현식 `c.+t`는 소문자 `c`가 나오고, 그 뒤에 한개 이상의 문자가 나온 후, 소문자 `t`가 나오는 패턴을 의미한다. 여기서 문자 `t`는 해당 문장의 제일 마지막 글자 `t`라는것을 명확히할 필요가 있다. + ++"c.+t" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/Dzf9Aa/1) + +### 2.3.3 물음표 + +정규 표현식에서 메타 문자 `?`는 선행 문자를 선택적으로 만드는 역할을 한다. 물음표는 부호 앞에 쓰여진 문자가 선택적으로 나오는 패턴을 나타내는데 사용된다. 예를 들어, 정규 표현식 `[T]?he`는 대문자 `T`가 선택적으로 나온 이후에, 그 뒤에 소문자 `h`, 그 뒤에 소문자 `e`가 나오는 패턴을 의미한다. + ++"[T]he" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/cIg9zm/1) + ++"[T]?he" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/kPpO2x/1) + +## 2.4 중괄호 + +정규 표현식에서 정량자(quantifier)라고도 불리는 중괄호는 하나의 문자 혹은 문자 집합으로 표시된 문자가 몇번 반복되는지 명시하는데 사용된다. 예를 들어, 정규 표현식 `[0-9]{2,3}`은 숫자 문자(0부터 9사이의 문자)가 최소 2번, 최대 3번 연속해서 나오는 문자열 패턴을 의미한다. + ++"[0-9]{2,3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Test the regular expression](https://regex101.com/r/juM86s/1) + +두번째 숫자를 생략하는 것이 가능하다. 예를 들어, 정규 표현식 `[0-9]{2,}`는 2번 이상의 숫자가 연속으로 나오는 패턴을 의미한다. 만약 여기서 쉼표를 삭제하는 경우, 정규 표현식 `[0-9]{3}`은 숫자가 정확히 3번 연속해서 나오는 패턴을 의미한다. + ++"[0-9]{2,}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Test the regular expression](https://regex101.com/r/Gdy4w5/1) + ++"[0-9]{3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Test the regular expression](https://regex101.com/r/Sivu30/1) + +## 2.5 캡쳐링 그룹 + +캡쳐링 그룹은 괄호 `(...)` 안에 쓰여진 하위 패턴들의 그룹이다. 위에서 논의했듯이, 정규 표현식에서 하나의 문자 뒤에 정량자(quantifier)를 넣는 경우에는 해당 문자의 반복을 나타낸다. 하지만, 만약 하나의 캡쳐링 그룹 뒤에 정량자를 넣는 경우에는 캡쳐링 그룹 전체의 반복을 나타내게 된다. 예를 들어, 정규 표현식 `(ab)*`는 문자 "ab"가 0번 이상 반복되는 패턴을 의미한다. 대안 부호인 `|` 또한 문자 그룹 내부에서 사용할 수 있다. 예를 들어, 정규 표현식 `(c|g|p)ar`은 소문자 `c`, `g` 혹은 `p`가 나온 이후에 문자 `a`가 나오고 그 뒤에 문자 `r`이 나오는 패턴을 의미한다. + ++"(c|g|p)ar" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/tUxrBG/1) + +캡처링 그룹은 부모 언어에서 사용하기 위해 문자를 일치시킬뿐만 아니라 문자를 캡처한다는 점에 유의해야 한다. 부모 언어는 파이썬이나 자바 스크립트 또는 함수 정의에서 정규 표현식을 구현하는 거의 모든 언어가 될 수 있다. + +### 2.5.1 논-캡쳐링 그룹 + +논-캡쳐링 그룹은 오직 문자열에 매칭되지만, 그룹을 캡쳐하지 않는 캡쳐링 그룹이다. 논-캡쳐링 그룹은 `(...)` 괄호안에 `?:` 로 표시된다. 예를 들어 정규식 `(?:c|g|p)ar` 는 `(c|g|p)ar`와 같은 문자열을 매칭하는 것에서 유사하지만, 캡쳐링 그룹을 만들지 않는다. + ++"(?:c|g|p)ar" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/Rm7Me8/1) + +논-캡처링 그룹은 찾기 및 변경 기능에서 사용하거나 캡처 그룹 함께 사용하여 다른 종류의 출력 생성시 overview를 유지할 때 유용하다. 또한 [4. 전후방탐색](#4-전후방탐색)를 보아라. + +## 2.6 대안 부호 + +정규 표현식에서 수직 막대 부호 `|`는 대안을 정의하는데 사용된다. 대안 부호는 여러개의 표현식들 사이의 조건과도 같다. 지금쯤 당신은 문자 집합(Character set)과 대안 부호가 동일하게 동작한다고 생각하고 있을 것이다. 하지만, 문자 집합과 대안 부호 사이의 가장 큰 차이점은 문자 집합은 문자 수준에서 동작하는 반면, 대안 부호는 표현식 수준에서 동작한다는 것이다. 예를 들어, 정규 표현식 `(T|t)he|car`는 대문자 `T` 혹은 소문자 `t`가 나오고 문자 `h`, 문자 `e`가 차례로 나오거나 문자 `c`, 문자 `a`, 문자 `r`이 차례로 나오는 패턴을 의미한다. + ++"(T|t)he|car" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/fBXyX0/1) + +## 2.7 특수 문자 이스케이핑 + +백 슬래시 `\`는 정규 표현식에서 다음에 나오는 부호를 이스케이핑하는데 사용된다. 백 슬래시는 예약 문자들인 `{ } [ ] / \ + * . $ ^ | ?`를 메타 부호가 아닌 문자 그 자체로 매칭되도록 명시한다. 특수 문자를 매칭 캐릭터로 사용하기 위해서는 백 슬래시 `\`를 해당 특수 문자 앞에 붙이면 된다. 예를 들어, 정규 표현식 `.`은 개행을 제외한 어떤 문자와 매칭된다. 입력 문자열에 포함된 `.` 문자를 매치시키는 정규 표현식 `(f|c|m)at\.?`은 소문자 `f`, `c` 또는 `m` 이후에 소문자 `a`와 `t`가 차례로 등장하고 이후에 문자 `.`가 선택적으로 나타나는 패턴을 의미한다. + ++"(f|c|m)at\.?" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/DOc5Nu/1) + +## 2.8 앵커 부호 + +정규 표현식에서 앵커는 매칭 문자가 표현식의 시작 문자인지 혹은 끝 문자인지 명시하는데 사용된다. 앵커는 두가지 종류가 있다: 첫번째 종류인 캐럿 부호 `^`는 매칭 문자가 입력 문자열의 첫 시작 문자인지 나타내는데 사용되며 두번째 종류인 달러 부호 `$`는 해당 매칭 문자가 입력 문자의 마지막 문자라는 것을 명시하는데 사용된다. + +### 2.8.1 캐럿 부호 + +캐럿 부호 `^`는 매칭 문자가 표현식의 시작이라는 것을 명시하는데 사용된다. 만약 (a가 시작 문자인지 확인하는) 정규 표현식 `^a`를 입력 문자열 `abc`에 적용하면, 이 정규 표현식은 `a`를 매칭 결과값으로 내보낸다. 반면, 정규 표현식 `^b`를 위의 입력 문자열에 적용하면, 아무런 매칭도 일어나지 않는다. 왜냐하면 입력 문자열 `abc`에서 "b"는 처음 시작 문자가 아니기 때문이다. 또 다른 정규 표현식인 `^(T|t)he`를 살펴보자. 이 정규 표현식은 대문자 `T` 또는 소문자 `t`가 입력 문자열의 시작으로 나오고, 그 뒤에 문자 `h`와 문자 `e`가 차례로 나오는 패턴을 의미한다. + ++"(T|t)he" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/5ljjgB/1) + ++"^(T|t)he" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/jXrKne/1) + +### 2.8.2 달러 부호 + +달러 부호 `$`는 입력 문자열의 마지막 문자가 매칭 문자로 끝나는지 확인하는데 사용된다. 예를 들어, 정규 표현식 `(at\.)$`는 소문자 `a`와 `t` 그리고 문자 `.`가 순서대로 입력 문자열의 맨 마지막에 나오는지 확인하는 패턴을 의미한다. + ++"(at\.)" => The fat cat. sat. on the mat. ++ +[Test the regular expression](https://regex101.com/r/y4Au4D/1) + ++"(at\.)$" => The fat cat. sat. on the mat. ++ +[Test the regular expression](https://regex101.com/r/t0AkOd/1) + +## 3. 단축형 문자열 집합 + +정규 표현식은 일반적으로 사용되는 문자열 집합들을 간편하게 사용할 수 있도록 여러 단축형들을 제공한다. 단축형 문자열 집합은 아래와 같다. + +|단축형|설명| +|:----:|----| +|.|개행을 제외한 모든 문자| +|\w|영숫자 문자와 매치: `[a-zA-Z0-9_]`| +|\W|영숫자 문자가 아닌 문자와 매치: `[^\w]`| +|\d|숫자와 매치: `[0-9]`| +|\D|숫자가 아닌 문자와 매치: `[^\d]`| +|\s|공백 문자와 매치: `[\t\n\f\r\p{Z}]`| +|\S|공백 문자가 아닌 문자와 매치: `[^\s]`| + +## 4. 전후방탐색 + +때때로 전후방탐색Lookaround이라고 알려진 후방탐색Lookbehind과 전방탐색Lookahead은 (패턴 매칭을 위해서 사용되지만 매칭된 리스트에는 포함되지 않는) **_넌-캡쳐링 그룹_** 의 특정 종류들이다. 전후방탐색은 하나의 패턴이 다른 특정 패턴 전이나 후에 나타나는 조건을 가지고 있을때 사용한다. 예를 들어, 우리가 입력 문자열 `$4.44 and $10.88`에 대해서 달러 부호 `$`이후에 나오는 모든 숫자를 매칭시키고 싶다고 하자. 이때 정규 표현식 `(?<=\$)[0-9\.]*`를 사용할 수 있다. 이 정규 표현식은 `$` 문자 뒤에 나오는 문자 `.`을 포함한 모든 숫자 문자를 의미한다. 다음은 정규 표현식에서 사용되는 전후방탐색들이다. + +|부호|설명| +|:----:|----| +|?=|긍정형 전방탐색| +|?!|부정형 전방탐색| +|?<=|긍정형 후방탐색| +|? +"[T|t]he(?=\sfat)" => The fat cat sat on the mat. ++"[T|t]he(?!\sfat)" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/V32Npg/1) + +### 4.3 긍정형 후방탐색 + +긍정형 후방탐색는 특정 패턴뒤에 나오는 문자열 매치를 가져오기 위해서 사용된다. 긍정형 후방탐색는 `(?<=...)`로 표시된다. 예를 들어, 정규 표현식 `(?<=[T|t]he\s)(fat|mat)`는 입력 문자열에서 `The` 혹은 `the` 뒤에 공백이 나오고, 그 뒤에 `fat` 또는 `mat`이 나오는 패턴을 의미한다. + ++"(?<=[T|t]he\s)(fat|mat)" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/avH165/1) + +### 4.4 부정형 후방탐색 + +부정형 후방탐색는 특정 패턴이 뒤에 나오지 않기를 바라는 상황에서 사용된다. 부정형 후방탐색는 `(? +"(?<![T|t]he\s)(cat)" => The cat sat on cat. +
+"The" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/dpQyf9/1) + +
+"/The/gi" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/ahfiuh/1) + +### 5.2 전체 검색 + +수정자 `g`는 첫번째 매칭후에 멈추지 않고 계속해서 모든 매칭을 검색하는 전체 검색을 수행하는데 사용된다. 예를 들어, 정규 표현식 `/.(at)/g`는 개행을 제외한 문자가 나오고, 그 뒤에 소문자 `a`, 소문자 `t`가 나오는 패턴을 의미한다. 여기에서 `g` 플래그를 정규 표현식의 마지막에 설정했기 때문에, 이 패턴은 입력 문자열 전체에서 나타나는 모든 패턴을 찾아낸다. + +
+"/.(at)/" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/jnk6gM/1) + +
+"/.(at)/g" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/dO1nef/1) + +### 5.3 멀티 라인 + +수정자 `m`은 멀티 라인 매치를 수행하는데 사용된다. 이전에 이야기 했던 것처럼, 앵커 `(^, $)`는 패턴의 시작과 끝을 확인하는데 사용된다. 하지만 만약 우리가 각 라인마다 이 앵커가 동작하게하고 싶으면 `m` 플래그를 설정하면된다. 예를 들어, 정규 표현식 `/at(.)?$/gm`은 소문자 `a`와 소문자 `t`가 차례로 나오고, 선택적으로 개행을 제외한 문자가 나오는 패턴을 의미한다. 여기서 플래그 `m`으로 인해서 정규 표현식 엔진은 입력 문자열의 각 라인에 대해서 해당 패턴을 매칭하게 된다. + +
+"/.at(.)?$/" => The fat + cat sat + on the mat. ++ +[Test the regular expression](https://regex101.com/r/hoGMkP/1) + +
+"/.at(.)?$/gm" => The fat + cat sat + on the mat. ++ +[Test the regular expression](https://regex101.com/r/E88WE2/1) + +## 6. 탐욕적 vs 게으른 매칭 +기본적으로 정규 표현식은 탐욕적(greedy) 매칭을 수행하는데, 이는 가능한 한 길게 매칭하는 것을 의미한다. 우리는 `?`를 사용하여 게으른(lazy) 방법 매칭할 수 있으며, 가능한 한 짧게 매칭하는 것을 의미한다. + +
+"/(.*at)/" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/AyAdgJ/1) + +
+"/(.*?at)/" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/AyAdgJ/2) + +## 기여 방법 + +* 이슈 리포팅 +* 코드 개선해서 풀 리퀘스트 열기 +* 소문내기 +* ziishaned@gmail.com 메일로 직접 연락하기 또는 [](https://twitter.com/ziishaned) + +## 라이센스 + +MIT © [Zeeshan Ahmad](https://twitter.com/ziishaned) diff --git a/translations/README-pl.md b/translations/README-pl.md new file mode 100644 index 00000000..92519d53 --- /dev/null +++ b/translations/README-pl.md @@ -0,0 +1,552 @@ +
+
+
+
+
+
+
+
+
+"the" => The fat cat sat on the mat. ++ +[Przetestuj wyrażenie](https://regex101.com/r/dmRygT/1) + +Wyrażenie regularne `123` pasuje do łańcucha `123`. Wyrażenie regularne +jest dopasowywane do danego łańcucha poprzez porównanie każdego znaku, +jeden po drugim, w wyrażeniu i łańcuchu. Wyrażenia są zwykle wrażliwe +na wielkość znaków, więc wyrażenie `The` nie pasuje do łańcucha `the`. + +
+"The" => The fat cat sat on the mat. ++ +[Przetestuj wyrażenie](https://regex101.com/r/1paXsy/1) + +## 2. Metaznaki + +Metaznaki to składowe elementy wyrażeń regularnych. Znaki te, nie oznaczają +siebie samych, są natomiast interpretowane w specjalny sposób. +Niektóre znaki mają specjalne znaczenie i są zapisywane w kwadratowych nawiasach. +Metaznaki to: + +|Metaznaki|Opis| +|:----:|----| +|.|Dowolny znak z wyjątkiem nowej linii.| +|[ ]|Zakres. Każdy znak zapisany w kwadratowym nawiasie.| +|[^ ]|Odwrócony zakres. Każdy znak, który nie znajduje się w kwadratowym nawiasie.| +|*|0 lub więcej poprzedzających znaków.| +|+|1 lub więcej poprzedzających znaków.| +|?|0 lub 1 poprzedzających znaków.| +|{n,m}|Minimum "n" ale nie więcej niż "m" poprzedzających znaków.| +|(xyz)|Grupowanie znaków. Znaki xyz dokładnie w tej kolejności.| +|||Alternatywa. Znaki przed symbolem lub za symbolem.| +|\|Znak ucieczki. Umożliwia używanie zarezerwowanych znaków
[ ] ( ) { } . * + ? ^ $ \ |
.|
+|^|Oznacza początek wzorca.|
+|$|Oznacza koniec wzorca.|
+
+## 2.1 Kropka
+
+Kropka `.` jest najprostszym przykładem metaznaku. Oznacza dowolny znak z wyłączeniem entera
+i znaków nowej linii. Na przykład, wyrażenie regularne `.ar` oznacza: dowolny znak, następującą
+po niej literę `a`, następującą po niej literę `r`.
+
++".ar" => The car parked in the garage. ++ +[Przetestuj wyrażenie](https://regex101.com/r/xc9GkU/1) + +## 2.2 Zestaw znaków + +Zestawy znaków nazywane też klasami znaków. Nawiasy kwadratowe służą do określenia zestawów znaków. +Użycie myślnika wewnątrz zestawu, określa jego zakres. Kolejność znaków w nawiasach kwadratowych +nie ma znaczenia. Na przykład wyrażenie `[Tt]he` oznacza: dużą literę `T` lub małą `t`, +następującą po niej literę `h`, następującą po niej literę `e`. + +
+"[Tt]he" => The car parked in the garage. ++ +[Przetestuj wyrażenie](https://regex101.com/r/2ITLQ4/1) + +Jednak kropka w zestawie znaków, oznacza dosłownie kropkę. Wyrażenie regularne +`ar[.]` oznacza: małą literę `a`, następującą po niej literę `r`, +następującą po niej `.` kropkę. + +
+"ar[.]" => A garage is a good place to park a car. ++ +[Przetestuj wyrażenie](https://regex101.com/r/wL3xtE/1) + +### 2.2.1 Odwrócony zestaw znaków + +Generalnie znak karety oznacza początek wyrażenia, ale gdy zostanie użyty zaraz +za otwierającym nawiasem kwadratowym, odwraca zestaw znaków. Na przykład +wyrażenie `[^c]ar` oznacza: każdy znak z wyjątkiem `c`, +następującą po niej literę `a`, następującą po niej literę `r`. + +
+"[^c]ar" => The car parked in the garage. ++ +[Przetestuj wyrażenie](https://regex101.com/r/nNNlq3/1) + +## 2.3 Powtórzenia + +Następujące metaznaki `+`, `*` czy `?` określają ile razy wzorzec może się powtórzyć. +Te metaznaki zachowują się różnie, w zależności od sytuacji. + +### 2.3.1 Gwiazdka + +Symbol `*` oznacza zero lub więcej powtórzeń poprzedzających znaków. Wyrażenie +regularne `a*` oznacza: zero lub więcej powtórzeń poprzedzającej małej +litery `a`. Ale jeśli występuje po zestawie znaków lub klasie, to oznacza +powtórzenia całego zestawu lub klasy. Na przykład, wyrażenie regularne +`[a-z]*` oznacza: każdy ciąg znaków pisany małymi literami. + +
+"[a-z]*" => The car parked in the garage #21. ++ +[Przetestuj wyrażenie](https://regex101.com/r/7m8me5/1) + +Symbol `*` może być użyty z metaznakiem `.` by oznaczyć każdy łańcuch +znaków `.*`. Symbol `*` może być użyty ze znakiem `\s` +by znaleźć łańcuch zawierający spacje. Na przykład, wyrażenie +`\s*cat\s*` oznacza: zero lub więcej spacji, następującą po niej małą literę `c`, +następującą po niej małą literę `a`, następującą po niej małą literę `t`, +następujące po niej zero lub więcej spacji. + +
+"\s*cat\s*" => The fat cat sat on the concatenation. ++ +[Przetestuj wyrażenie](https://regex101.com/r/gGrwuz/1) + +### 2.3.2 Plus + +Symbol `+` oznacza jeden lub więcej powtórzeń poprzedzających znaków. Na przykład, +wyrażenie `c.+t` oznacza: małą literę `c`, następujący po niej przynajmniej jeden +dowolny znak, następującą po nim małą literę `t`. W tym wypadku `t` jest ostatnim +`t` w zdaniu. + +
+"c.+t" => The fat cat sat on the mat. ++ +[Przetestuj wyrażenie](https://regex101.com/r/Dzf9Aa/1) + +### 2.3.3 Znak zapytania + +W wyrażeniach regularnych znak `?` sprawia, że poprzedzający znak jest opcjonalny. +Ten symbol oznacza zero lub jedno wystąpienie poprzedzającego znaku. Na przykład, +wyrażenie regularne `[T]?he` oznacza: opcjonalną dużą literę `T`, następującą +po niej małą literę `h`, następującą po niej małą literę `e`. + +
+"[T]he" => The car is parked in the garage. ++ +[Przetestuj wyrażenie](https://regex101.com/r/cIg9zm/1) + +
+"[T]?he" => The car is parked in the garage. ++ +[Przetestuj wyrażenie](https://regex101.com/r/kPpO2x/1) + +## 2.4 Klamry + +W wyrażeniach regularnych, klamry zwane również kwantyfikatorami, używane są +do określenia, ile razy znak lub grupa znaków może się powtórzyć. +Na przykład wyrażenie regularne `[0-9]{2,3}` oznacza: przynajmniej +2 znaki, ale nie więcej niż 3 (znaki z zakresu od 0 do 9). + +
+"[0-9]{2,3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Przetestuj wyrażenie](https://regex101.com/r/juM86s/1) + +Możemy opuścić drugą liczbę. Na przykład regularne wyrażenie `[0-9]{2,}` +oznacza: 2 lub więcej znaków. Jeżeli dodatkowo usuniemy przecinek, +to wyrażenie `[0-9]{3}` oznacza: dokładnie 3 znaki z zakresu 0 do 9. + +
+"[0-9]{2,}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Przetestuj wyrażenie](https://regex101.com/r/Gdy4w5/1) + +
+"[0-9]{3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Przetestuj wyrażenie](https://regex101.com/r/Sivu30/1) + +## 2.5 Grupa znaków + +Grupa znaków to grupa podwzorców, które zapisywane są w nawiasach `(...)`. +Jak wspominaliśmy wyżej, jeśli w wyrażeniu regularnym wstawimy kwantyfikator po +znaku, wtedy powtórzy on ten znak. Ale gdy wstawimy kwantyfikator po grupie znaków, +wtedy cała grupa zostanie powtórzona. Na przykład wyrażenie regularne `(ab)*` +oznacza zero lub więcej powtórzeń grupy "ab". Możemy także użyć metaznaku +alternatywy `|` wewnątrz grupy. Na przykład wyrażenie `(c|g|p)ar` oznacza: małą literę `c`, +`g` lub `p`, następującą po niej literę `a`, następującą po niej literę `r`. + +
+"(c|g|p)ar" => The car is parked in the garage. ++ +[Przetestuj wyrażenie](https://regex101.com/r/tUxrBG/1) + +## 2.6 Alternatywa + +W wyrażeniach regularnych pionowa kreska `|` oznacza alternatywę. +Działa jak warunek pomiędzy różnymi wyrażeniami. Teraz możesz pomyśleć, że +to działa tak samo jak zestaw znaków. Różnica polega na tym, że zestaw znaków +działa na poziomie znaków, natomiast alternatywa na poziomie wyrażenia. Na przykład +wyrażenie regularne `(T|t)he|car` oznacza: dużą literę `T` lub małą `t`, +następującą po niej literę `h`, następującą po niej literę `e` lub `c`, następującą +po niej literę `a`, następującą po niej literę `r`. + +
+"(T|t)he|car" => The car is parked in the garage. ++ +[Przetestuj wyrażenie](https://regex101.com/r/fBXyX0/1) + +## 2.7 Znak ucieczki + +Ukośnik `\` w wyrażeniach regularnych jest znakiem ucieczki. Pozwala on +używać w wyrażeniu zarezerwowanych znaków takich jak `{ } [ ] / \ + * . $ ^ | ?`. +Aby użyć znaku specjalnego w wyrażeniu, postaw `\` przed nim. + +Na przykład wyrażenie `.` dopasowuje każdy znak z wyjątkiem nowej linii. +Żeby dopasować kropkę `.` w wyrażeniu regularnym, trzeba wstawić przed nią ukośnik. +Wyrażenie `(f|c|m)at\.?` oznacza: małe litery `f` lub `c` lub `m`, następującą po niej +literę `a`, następującą po niej literę `t`, następującą kropkę `.`, która jest opcjonalna. + +
+"(f|c|m)at\.?" => The fat cat sat on the mat. ++ +[Przetestuj wyrażenie](https://regex101.com/r/DOc5Nu/1) + +## 2.8 Kotwice + +W wyrażeniach regularnych używamy kotwic aby sprawdzić czy dopasowywany symbol +jest pierwszym lub ostatnim symbolem w łańcuchu. Są dwa typy: pierwszy to +kareta `^`, która sprawdza czy znak jest początkiem łańcucha, drugi to dolar `$`, +który sprawdza czy znak jest ostatnim elementem łańcucha. + +### 2.8.1 Kareta + +Kareta `^` sprawdza czy znak jest początkiem łańcucha. Jeżeli użyjemy takiego +wyrażenia `^a` (jeśli a jest pierwszym znakiem) na łańcuchu `abc` to dopasuje +nam `a`. Ale jeśli użyjemy takiego wyrażenia `^b` na tym samym łańcuchu, to nie +zwróci nam nic. Ponieważ w łańcuchu `abc` "b" nie jest pierwszym symbolem. +Spójrzmy teraz na wyrażenie `^(T|t)he` które oznacza: dużą literę `T` lub małą +`t`, która jest początkiem łańcucha, następującą po niej literę `h`, następującą +po niej literę `e`. + +
+"(T|t)he" => The car is parked in the garage. ++ +[Przetestuj wyrażenie](https://regex101.com/r/5ljjgB/1) + +
+"^(T|t)he" => The car is parked in the garage. ++ +[Przetestuj wyrażenie](https://regex101.com/r/jXrKne/1) + +### 2.8.2 Dolar + +Symbol dolara `$` używany jest do sprawdzenia czy dopasowywany znak jest ostatni +w łańcuchu. Na przykład, wyrażenie regularne `(at\.)$` oznacza: małą literę `a`, +następującą po niej literę `t`, następującą po niej kropkę `.` i na dodatek +dopasowanie musi być końcem łańcucha. + +
+"(at\.)" => The fat cat. sat. on the mat. ++ +[Przetestuj wyrażenie](https://regex101.com/r/y4Au4D/1) + +
+"(at\.)$" => The fat cat. sat. on the mat. ++ +[Przetestuj wyrażenie](https://regex101.com/r/t0AkOd/1) + +## 3. Skróty + +W wyrażeniach regularnych znajdziemy także skróty dla popularnych zestawów znaków, +które ułatwiają pracę z wyrażeniami regularnymi. Skróty wyglądają następująco: + +|Skrót|Opis| +|:----:|----| +|.|Każdy znak z wyjątkiem nowej linii| +|\w|Znaki alfanumeryczne: `[a-zA-Z0-9_]`| +|\W|Znaki nie alfanumeryczne: `[^\w]`| +|\d|Cyfry: `[0-9]`| +|\D|Nie cyfry: `[^\d]`| +|\s|Dowolny biały znak: `[\t\n\f\r\p{Z}]`| +|\S|Każdy znak oprócz białych: `[^\s]`| + +## 4. Lookaround + +Lookbehind i lookahead (nazywane również lookaround) to specyficzne typy +***niezwracających grup*** (dopasowują wzorzec, ale nie zwracają wartości). +Lookaround używane są w sytuacji, gdy mamy wzorzec i jest on poprzedzony innym wzorcem, +lub następuje po nim kolejny wzorzec. Na przykład, chcemy mieć wszystkie +numery, które są poprzedzone znakiem `$` w takim łańcuchu `$4.44 and $10.88`. +Użyjemy takiego wyrażenia regularnego `(?<=\$)[0-9\.]*` które oznacza: znajdź +wszystkie liczby ze znakiem `.` poprzedzone znakiem `$`. W wyrażeniach regularnych +wyróżniamy: + +|Symbol|Opis| +|:----:|----| +|?=|Lookahead| +|?!|Odwrócony lookahead| +|?<=|Lookbehind| +|? +"(T|t)he(?=\sfat)" => The fat cat sat on the mat. + + +[Przetestuj wyrażenie](https://regex101.com/r/IDDARt/1) + +### 4.2 Odwrócony lookahead + +Używany jest, gdy potrzebujemy dopasowania z łańcucha, po których nie następują +żadne wzorce. Odwrócony lookahead definiujemy w nawiasach, stosując znak negacji +`!` po znaku zapytania, na przykład: `(?!...)`. Popatrzmy na następujące wyrażenie +`(T|t)he(?!\sfat)` które oznacza: znajdź wszystkie słowa `The` lub `the` w łańcuchu, +po których nie następuje słowo `fat`, poprzedzone spacją. + +
+"(T|t)he(?!\sfat)" => The fat cat sat on the mat. ++ +[Przetestuj wyrażenie](https://regex101.com/r/V32Npg/1) + +### 4.3 Lookbehind + +Lookbehind używany jest do odnalezienia wszystkich dopasowań poprzedzonych konkretnym +wzorcem. Wyrażenie lookbehind zapisujemy tak: `(?<=...)`. Na przykład, wyrażenie +`(?<=(T|t)he\s)(fat|mat)` oznacza: znajdź wszystkie słowa `fat` lub `mat` w łańcuchu, +które znajdują się po słowach `The` lub `the`. + +
+"(?<=(T|t)he\s)(fat|mat)" => The fat cat sat on the mat. ++ +[Przetestuj wyrażenie](https://regex101.com/r/avH165/1) + +### 4.4 Odwrócony lookbehind + +Odwrócony używany jest do odnalezienia wszystkich dopasowań niepoprzedzonych konkretnym +wzorcem. Odwrócony lookbehind zapisujemy tak: `(? +"(?<!(T|t)he\s)(cat)" => The cat sat on cat. + + +[Przetestuj wyrażenie](https://regex101.com/r/8Efx5G/1) + +## 5. Flagi + +Flagi nazywane są także modyfikatorami, ponieważ zmieniają wynik wyrażenia regularnego. +Flagi mogą być używane w każdej kombinacji i są integralną częścią wyrażeń regularnych. + +|Flaga|Opis| +|:----:|----| +|i|Wielkość znaków: Sprawia, że dopasowanie nie jest wrażliwe na wielkość znaków.| +|g|Przeszukanie globalne: Wyszukiwanie wzorca w całym łańcuchu.| +|m|Multilinia: Sprawia, że kotwice działają na każdej linii.| + +### 5.1 Wielkość znaków + +Modyfikator `i` używany jest, gdy wielkość liter nie ma znaczenia. Na przykład +wyrażenie `/The/gi` oznacza: dużą literę `T`, następującą po niej literę `h`, +następującą po niej literę `e`. A na końcu wyrażenia, flaga `i` żeby ignorować +wielkość znaków. Jak widać, została też użyta flaga `g` ponieważ chcemy przeszukać +cały łańcuch. + +
+"The" => The fat cat sat on the mat. ++ +[Przetestuj wyrażenie](https://regex101.com/r/dpQyf9/1) + +
+"/The/gi" => The fat cat sat on the mat. ++ +[Przetestuj wyrażenie](https://regex101.com/r/ahfiuh/1) + +### 5.2 Przeszukiwanie globalne + +Modyfikator `g` używany jest do przeszukiwania całego łańcucha (znajdź wszystko, +a nie tylko zatrzymuj się na pierwszym). Na przykład wyrażenie `/.(at)/g` +oznacza: każdy znak z wyjątkiem nowej linii, następującą po nim literę `a`, +następującą po niej literę `t`. Ponieważ użyliśmy na końcu wyrażenia flagi `g`, +wyszukane zostaną wszystkie dopasowania w łańcuchu, a nie tylko pierwszy (domyślne zachowanie). + +
+"/.(at)/" => The fat cat sat on the mat. ++ +[Przetestuj wyrażenie](https://regex101.com/r/jnk6gM/1) + +
+"/.(at)/g" => The fat cat sat on the mat. ++ +[Przetestuj wyrażenie](https://regex101.com/r/dO1nef/1) + +### 5.3 Multilinia + +Modyfikator `m` używany jest do dopasowywania w wielu liniach. Jak wspominaliśmy +wcześniej, kotwice `(^, $)` używane są do sprawdzania czy wzorzec jest początkiem +lub końcem łańcucha. Jeśli chcemy, żeby kotwice zadziałały w każdej linii, używamy +wtedy flagi `m`. Na przykład wyrażenie `/at(.)?$/gm` oznacza: małą literę `a`, +następującą po niej małą literę `t`, opcjonalnie dowolny znak z wyjątkiem nowej linii. +I ponieważ użyliśmy flagi `m` dopasowywane będą wzorce na końcu każdej linii w łańcuchu. + +
+"/.at(.)?$/" => The fat + cat sat + on the mat. ++ +[Przetestuj wyrażenie](https://regex101.com/r/hoGMkP/1) + +
+"/.at(.)?$/gm" => The fat + cat sat + on the mat. ++ +[Przetestuj wyrażenie](https://regex101.com/r/E88WE2/1) + +## Kontrybucja + +* Zgłaszanie błędów +* Otwieranie pull request z poprawkami +* Dzielenie się poradnikiem +* Skontaktuj się ze mną ziishaned@gmail.com lub [](https://twitter.com/ziishaned) + +## Licencja + +MIT © [Zeeshan Ahmad](https://twitter.com/ziishaned) diff --git a/translations/README-pt_BR.md b/translations/README-pt_BR.md new file mode 100644 index 00000000..653138f1 --- /dev/null +++ b/translations/README-pt_BR.md @@ -0,0 +1,452 @@ +
+
+
+
+
+
+
+
+
+"the" => The fat cat sat on the mat. ++ +[Teste a RegExp](https://regex101.com/r/dmRygT/1) + +A expressão regular `123` corresponde à string `123`. A expressão regular é comparada com uma string de entrada, comparando cada caractere da expressão regular para cada caractere da string de entrada, um após o outro. Expressões regulares são normalmente case-sensitive (sensíveis a maiúsculas), então a expressão regular `The` não vai bater com a string `the`. + +
+"The" => The fat cat sat on the mat. ++ +[Teste a RegExp](https://regex101.com/r/1paXsy/1) + +## 2. Metacaracteres + +Metacaracteres são elementos fundamentais das expressões regulares. Metacaracteres não representam a si mesmos mas, ao invés disso, são interpretados de uma forma especial. Alguns metacaracteres tem um significado especial e são escritos dentro de colchetes. +Os metacaracteres são os seguintes: + +|Metacaracter|Descrição| +|:----:|----| +|.|Corresponde a qualquer caractere, exceto uma quebra de linha| +|[ ]|Classe de caracteres. Corresponde a qualquer caractere contido dentro dos colchetes.| +|[^ ]|Classe de caracteres negada. Corresponde a qualquer caractere que não está contido dentro dos colchetes.| +|*|Corresponde a 0 ou mais repetições do símbolo anterior.| +|+|Corresponde a 1 ou mais repetições do símbolo anterior.| +|?|Faz com que o símbolo anterior seja opcional.| +|{n,m}|Chaves. Corresponde a no mínimo "n" mas não mais que "m" repetições do símbolo anterior.| +|(xyz)|Grupo de caracteres. Corresponde aos caracteres xyz nesta exata ordem.| +|||Alternância. Corresponde aos caracteres antes ou os caracteres depois do símbolo| +|\|Escapa o próximo caractere. Isso permite você utilizar os caracteres reservados
[ ] ( ) { } . * + ? ^ $ \ |
|
+|^|Corresponde ao início da entrada.|
+|$|Corresponde ao final da entrada.|
+
+## 2.1 Ponto final
+
+O ponto final `.` é um simples exemplo de metacaracteres. O metacaractere `.` corresponde a qualquer caractere sozinho. Ele não se iguala ao Enter e à quebra de linha. Por exemplo, a expressão regular `.ar` significa: qualquer caractere, seguido da letra `a`, seguida da letra `r`.
+
++".ar" => The car parked in the garage. ++ +[Teste a RegExp](https://regex101.com/r/xc9GkU/1) + +## 2.2 Conjunto de caracteres + +Conjuntos de caracteres também são chamados de classes de caracteres. Utilizamos colchetes para especificar conjuntos de caracteres. Use um hífen dentro de um conjunto de caracteres para especificar o intervalo de caracteres. A ordem dos caracteres dentro dos colchetes não faz diferença. Por exemplo, a expressão regular `[Tt]he` significa: um caractere maiúsculo `T` ou minúsculo `t`, seguido da letra `h`, seguida da letra `e`. + +
+"[Tt]he" => The car parked in the garage. ++ +[Teste a RegExp](https://regex101.com/r/2ITLQ4/1) + +No entanto, um ponto final dentro de um conjunto de caracteres, significa apenas um ponto final. A expressão regular `ar[.]` significa: o caractere minúsculo `a`, seguido da letra `r`, seguida pelo caractere de ponto final `.`. + +
+"ar[.]" => A garage is a good place to park a car. ++ +[Teste a RegExp](https://regex101.com/r/wL3xtE/1) + +### 2.2.1 Conjunto de caracteres negados + +No geral, o símbolo do circunflexo representa o início da string, mas quando está logo após o colchete de abertura, ele faz a negação do conjunto de caracteres. Por exemplo, a expressão regular `[^c]ar` significa: qualquer caractere com exceção do `c`, seguido pelo caractere `a`, seguido da letra `r`. + +
+"[^c]ar" => The car parked in the garage. ++ +[Teste a RegExp](https://regex101.com/r/nNNlq3/1) + +## 2.3 Repetições + +Seguindo os metacaracteres `+`, `*` ou `?` são utilizados para especificar quantas vezes um sub-padrão pode ocorrer. Esses metacaracteres atuam de formas diferentes em diferentes situações. + +### 2.3.1 O Asterisco + +O símbolo `*` corresponde a zero ou mais repetições do padrão antecedente. A expressão regular `a*` significa: zero ou mais repetições do caractere minúsculo precedente `a`. Mas se o asterisco aparecer depois de um conjunto de caracteres, ou classe de caracteres, ele irá procurar as repetições de todo o conjunto. Por exemplo, a expressão regular `[a-z]*` significa: qualquer quantidade de letras minúsculas numa linha. + +
+"[a-z]*" => The car parked in the garage #21. ++ +[Teste a RegExp](https://regex101.com/r/7m8me5/1) + +O símbolo `*` pode ser usado junto do metacaractere `.` para encontrar qualquer string de caracteres `.*`. O símbolo `*` pode ser usado com o caractere de espaço em branco `\s` para encontrar uma string de caracteres em branco. Por exemplo, a expressão `\s*cat\s*` significa: zero ou mais espaços, seguidos do caractere minúsculo `c`, seguido do caractere minúsculo `a`, seguido do caractere minúsculo `t`, seguido de zero ou mais espaços. + +
+"\s*cat\s*" => The fat cat sat on the concatenation. ++ +[Teste a RegExp](https://regex101.com/r/gGrwuz/1) + +### 2.3.2 O Sinal de Adição + +O símbolo `+` corresponde a uma ou mais repetições do caractere anterior. Por exemplo, a expressão regular `c.+t` significa: a letra minúscula `c`, seguida por pelo menos um caractere, seguido do caractere minúsculo `t`. + +
+"c.+t" => The fat cat sat on the mat. ++ +[Teste a RegExp](https://regex101.com/r/Dzf9Aa/1) + +### 2.3.3 O Ponto de Interrogação + +Em expressões regulares, o metacaractere `?` faz o caractere anterior ser opcional. Esse símbolo corresponde a zero ou uma ocorrência do caractere anterior. Por exemplo, a expressão regular `[T]?he` significa: A letra maiúsculo `T` opcional, seguida do caractere minúsculo `h`, seguido do caractere minúsculo `e`. + +
+"[T]he" => The car is parked in the garage. ++ +[Teste a RegExp](https://regex101.com/r/cIg9zm/1) + +
+"[T]?he" => The car is parked in the garage. ++ +[Teste a RegExp](https://regex101.com/r/kPpO2x/1) + +## 2.4 Chaves + +Em expressões regulares, chaves, que também são chamadas de quantificadores, são utilizadas para especificar o número de vezes que o caractere, ou um grupo de caracteres, pode se repetir. Por exemplo, a expressão regular `[0-9]{2,3}` significa: Encontre no mínimo 2 dígitos, mas não mais que 3 (caracteres no intervalo de 0 a 9). + +
+"[0-9]{2,3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Teste a RegExp](https://regex101.com/r/juM86s/1) + +Nós podemos retirar o segundo número. Por exemplo, a expressão regular `[0-9]{2,}` significa: Encontre 2 ou mais dígitos. Se removermos a vírgula a expressão regular `[0-9]{3}` significa: Encontre exatamente 3 dígitos. + +
+"[0-9]{2,}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Teste a RegExp](https://regex101.com/r/Gdy4w5/1) + +
+"[0-9]{3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Teste a RegExp](https://regex101.com/r/Sivu30/1) + +## 2.5 Grupo de Caracteres + +Grupo de caracteres é um grupo de sub-padrão que é escrito dentro de parênteses `(...)`. Como falamos antes, se colocaramos um quantificador depois de um caractere, ele irá repetir o caractere anterior. Mas se colocarmos um quantificador depois de um grupo de caracteres, ele irá repetir todo o conjunto. Por exemplo, a expressão regular `(ab)*` corresponde a zero ou mais repetições dos caracteres "ab". Nós também podemos usar o metacaractere de alternância `|` dentro de um grupo de caracteres. Por exemplo, a expressão regular `(c|g|p)ar` significa: caractere minúsculo `c`, `g` ou `p`, seguido do caractere `a`, seguido do caractere `r`. + +
+"(c|g|p)ar" => The car is parked in the garage. ++ +[Teste a RegExp](https://regex101.com/r/tUxrBG/1) + +## 2.6 Alternância + +Em expressões regulares, a barra vertical `|` é usada para definir alternância. Alternância é como uma condição entre múltiplas expressões. Agora, você pode estar pensando que um conjunto de caracteres e a alternância funcionam da mesma forma. Mas a grande diferença entre eles é que o conjunto de caracteres trabalha no nível de caracteres, enquanto a alternância trabalha no nível das expressões. Por exemplo, a expressão regular `(T|t)he|car` significa: o caractere maiúsculo `T` ou minúsculo `t`, seguido do caractere minúsculo `h`, seguido do caractere minúsculo `e` ou o caractere minúsculo `c`, seguido do caractere minúsculo `a`, seguido do caractere minúsculo `r`. + +
+"(T|t)he|car" => The car is parked in the garage. ++ +[Teste a RegExp](https://regex101.com/r/fBXyX0/1) + +## 2.7 Escapando Caracteres Especiais + +Em expressões regulares, a contrabarra `\` é usada para escapar o próximo caractere. Isso possibilita especificar um símbolo como um caractere correspondente, incluindo os caracteres reservados `{ } [ ] / \ + * . $ ^ | ?`. Para usar um caractere especial como um caractere correspondente, utilize `\` antes dele. Por exemplo, a expressão regular `.` é usada para encontrar qualquer caractere, exceto nova linha. Agora, para encontrar `.` em uma string de entrada, a expressão regular `(f|c|m)at\.?` significa: letra minúscula `f`, `c` ou `m`, seguida do caractere minúsculo `a`, seguido da letra minúscula `t`, seguida do caractere `.` opcional. + +
+"(f|c|m)at\.?" => The fat cat sat on the mat. ++ +[Teste a RegExp](https://regex101.com/r/DOc5Nu/1) + +## 2.8 Âncoras + +Em empressões regulares, usamos âncoras para verificar se o caractere encontrado está no início ou no final da string de entrada. As âncoras podem ser de dois tipos: O primeiro tipo é o Acento Circunflexo `^`, que verifica se o caractere encontrado está no início da string de entrada, e o segundo tipo é o Sinal de Dólar `$`, que verifica se o caractere encontrado é o último caractere da string. + +### 2.8.1 Acento Circunflexo + +O símbolo do Acento Circunflexo `^` é usado para verificar se o caractere encontrado é o primeiro caractere da string de entrada. Se aplicarmos a seguinte expressão regular `^a` (se a é o primeiro caractere) à string de entrada `abc`, ela encontra o `a`. Mas se nós aplicarmos a expressão regular `^b` na mesma string, ela não encontrará nada. Isso acontece porque, na string `abc`, "b" não é o caractere inicial. Vamos dar uma olhada em outra expressão regular, `^(T|t)he` que significa: o caractere maiúsculo `T` ou o caractere minúsculo `t` que é o primeiro símbolo da string de entrada, seguido do caractere minúsculo `h`, seguido do caractere minúsculo `e`. + +
+"(T|t)he" => The car is parked in the garage. ++ +[Teste a RegExp](https://regex101.com/r/5ljjgB/1) + +
+"^(T|t)he" => The car is parked in the garage. ++ +[Teste a RegExp](https://regex101.com/r/jXrKne/1) + +### 2.8.2 Sinal de Dólar + +O símbolo do Sinal de Dólar `$` é usado para verificar se o caractere encontrado é o último caractere da string de entrada. Por exemplo, a expressão regular `(at\.)$` significa: um caractere minúsculo `a`, seguido do caractere minúsculo `t`, seguido de um ponto final `.` e o grupo deve estar no final da string. + +
+"(at\.)" => The fat cat. sat. on the mat. ++ +[Teste a RegExp](https://regex101.com/r/y4Au4D/1) + +
+"(at\.)$" => The fat cat. sat. on the mat. ++ +[Teste a RegExp](https://regex101.com/r/t0AkOd/1) + +## 3. Forma Abreviada de Conjunto de Caracteres + +As expressões regulares fornecem abreviações para conjuntos de caracteres comumente usados, que oferecem atalhos convenientes para expressões regulares comumente usadas. As abreviações são as seguintes: + +|Abreviação|Descrição| +|:----:|----| +|.|Qualquer caractere, exceto nova linha| +|\w|Corresponde a caracteres alfanuméricos: `[a-zA-Z0-9_]`| +|\W|Corresponde a caracteres não alfanuméricos: `[^\w]`| +|\d|Corresponde a dígitos: `[0-9]`| +|\D|Corresponde a não dígitos: `[^\d]`| +|\s|Corresponde a caracteres de espaços em branco: `[\t\n\f\r\p{Z}]`| +|\S|Corresponde a caracteres de espaços não em branco: `[^\s]`| + +## 4. Olhar ao Redor + +Lookbehind (olhar atrás) e lookahead (olhar à frente), às vezes conhecidos como lookarounds (olhar ao redor), são tipos específicos de ***grupo de não captura*** (utilizado para encontrar um padrão, mas não incluí-lo na lista de ocorrências). Lookarounds são usados quando temos a condição de que determinado padrão seja precedido ou seguido de outro padrão. Por exemplo, queremos capturar todos os números precedidos do caractere `$` da seguinte string de entrada: `$4.44 and $10.88`. Vamos usar a seguinte expressão regular `(?<=\$)[0-9\.]*` que significa: procure todos os números que contêm o caractere `.` e são precedidos pelo caractere `$`. A seguir estão os lookarounds que são utilizados em expressões regulares: + +|Símbolo|Descrição| +|:----:|----| +|?=|Lookahead Positivo| +|?!|Lookahead Negativo| +|?<=|Lookbehind Positivo| +|? +"[T|t]he(?=\sfat)" => The fat cat sat on the mat. + + +[Teste a RegExp](https://regex101.com/r/IDDARt/1) + +### 4.2 Lookahead Negativo + +O lookahead negativo é usado quando nós precisamos encontrar todas as ocorrências da string de entrada que não são seguidas por um determinado padrão. O lookahead negativo é definido da mesma forma que definimos o lookahead positivo, mas a única diferença é que, no lugar do sinal de igual `=`, usamos o caractere de negação `!`, ex.: `(?!...)`. Vamos dar uma olhada na seguinte expressão regular `[T|t]he(?!\sfat)`, que significa: obtenha as palavras `The` ou `the` da string de entrada que não são seguidas pela palavra `fat`, precedida de um caractere de espaço. + +
+"[T|t]he(?!\sfat)" => The fat cat sat on the mat. ++ +[Teste a RegExp](https://regex101.com/r/V32Npg/1) + +### 4.3 Lookbehind Positivo + +Lookbehind positivo é usado para encontrar todas as ocorrências que são precedidas por um padrão específico. O lookbehind positivo é indicado por `(?<=...)`. Por exemplo, a expressão regular `(?<=[T|t]he\s)(fat|mat)` significa: obtenha todas as palavras `fat` ou `mat` da string de entrada, que estão depois das palavras `The` ou `the`. + +
+"(?<=[T|t]he\s)(fat|mat)" => The fat cat sat on the mat. ++ +[Teste a RegExp](https://regex101.com/r/avH165/1) + +### 4.4 Lookbehind Negativo + +Lookbehind negativo é usado para encontrar todas as ocorrências que não são precedidas por um padrão específico. O lookbehind negativo é indicado por `(? +"(?<![T|t]he\s)(cat)" => The cat sat on cat. + + +[Teste a RegExp](https://regex101.com/r/8Efx5G/1) + +## 5. Flags + +Flags (sinalizadores) também são chamados de modificadores, porque eles modificam o resultado da expressão regular. Essas flags podem ser usadas em qualquer ordem ou combinação, e são uma parte integrante da RegExp. + +|Flag|Descrição| +|:----:|----| +|i|Case insensitive: Define que o padrão será case-insensitive.| +|g|Busca global: Procura o padrão em toda a string de entrada.| +|m|Multilinhas: Os metacaracteres de âncora funcionam em cada linha.| + +### 5.1 Indiferente a Maiúsculas + +O modificador `i` é usado para tornar o padrão case-insensitive. Por exemplo, a expressão regular `/The/gi` significa: a letra maiúscula `T`, seguida do caractere minúsculo `h`, seguido do caractere `e`. E ao final da expressão regular, a flag `i` diz ao motor de expressões regulares para ignorar maiúsculas e minúsculas. Como você pode ver, nós também determinamos a flag `g` porque queremos procurar o padrão em toda a string de entrada. + +
+"The" => The fat cat sat on the mat. ++ +[Teste a RegExp](https://regex101.com/r/dpQyf9/1) + +
+"/The/gi" => The fat cat sat on the mat. ++ +[Teste a RegExp](https://regex101.com/r/ahfiuh/1) + +### 5.2 Busca Global + +O modificador `g` é usado para realizar uma busca global (encontrar todas as ocorrências sem parar na primeira encontrada). Por exemplo, a expressão regular `/.(at)/g` significa: qualquer caractere, exceto nova linha, seguido do caractere minúsculo `a`, seguido do caractere minúsculo `t`. Por causa da flag `g` no final da expressão regular, agora ela vai encontrar todas as ocorrências em toda a string de entrada. + +
+"/.(at)/" => The fat cat sat on the mat. ++ +[Teste a RegExp](https://regex101.com/r/jnk6gM/1) + +
+"/.(at)/g" => The fat cat sat on the mat. ++ +[Teste a RegExp](https://regex101.com/r/dO1nef/1) + +### 5.3 Multilinhas + +O modificador `m` é usado para realizar uma busca em várias linhas. Como falamos antes, as âncoras `(^, $)` são usadas para verificar se o padrão está no início ou no final da string de entrada respectivamente. Mas se queremos que as âncoras funcionem em cada uma das linhas, usamos a flag `m`. Por exemplo, a expressão regular `/.at(.)?$/gm` significa: o caractere minúsculo `a`, seguido do caractere minúsculo `t`, opcionalmente seguido por qualquer caractere, exceto nova linha. E por causa da flag `m`, agora o motor de expressões regulares encontra o padrão no final de cada uma das linhas da string. + +
+"/.at(.)?$/" => The fat + cat sat + on the mat. ++ +[Teste a RegExp](https://regex101.com/r/hoGMkP/1) + +
+"/.at(.)?$/gm" => The fat + cat sat + on the mat. ++ +[Teste a RegExp](https://regex101.com/r/E88WE2/1) + +### 6. Guloso vs Não-Guloso + +Por padrão, uma regex irá realizar uma consulta gulosa, isto significa que a busca irá capturar ao padrão mais longo possível. Nós podemos usar `?` para buscar de uma forma não-gulosa, isto significa que a busca irá capturar ao padrão mais curto possível. + +
+"/(.*at)/" => The fat cat sat on the mat.+ + +[Teste a RegExp](https://regex101.com/r/AyAdgJ/1) + +
+"/(.*?at)/" => The fat cat sat on the mat.+ + +[Teste a RegExp](https://regex101.com/r/AyAdgJ/2) + + +## Contribution + +* Reporte bugs +* Abra pull request com melhorias +* Espalhe a palavra +* Me encontre diretamente em ziishaned@gmail.com ou [](https://twitter.com/ziishaned) + +## Licença + +MIT © [Zeeshan Ahmad](https://twitter.com/ziishaned) diff --git a/translations/README-ru.md b/translations/README-ru.md new file mode 100644 index 00000000..922715f3 --- /dev/null +++ b/translations/README-ru.md @@ -0,0 +1,602 @@ +
+
+
+
+
+
+
+
+"the" => The fat cat sat on the mat. ++ +[Запустить регулярное выражение](https://regex101.com/r/dmRygT/1) + +Регулярное выражение `123` соответствует строке `123`. Регулярное выражение +сопоставляется с входной строкой посимвольно. Каждый символ в регулярном +выражении сравнивается с каждым символом во входной строке, один символ за +другим. Регулярные выражения обычно чувствительны к регистру, поэтому регулярное +выражение `The` не будет соответствовать строке `the`. + +
+"The" => The fat cat sat on the mat. ++ +[Запустить регулярное выражение](https://regex101.com/r/1paXsy/1) + +## 2. Метасимволы + +Метасимволы — это строительные блоки для регулярных выражений. Метасимволы не +ищутся в строке как есть, они интерпретируются особым образом. Некоторые +метасимволы имеют особое значение и пишутся в квадратных скобках. Существуют +следующие метасимволы: + +|Метасимвол|Описание| +|:----:|----| +|.|Точка соответствует любому отдельному символу, кроме перевода строки.| +|[ ]|Класс символов. Заменяет любой из символов, заключенных в квадратных скобках.| +|[^ ]|Отрицание класа символов. Соответствует любом символу, не содержащемуся в квадратных скобках.| +|\*|Искать 0 или более повторов предыдущего символа.| +|+|Искать 1 или более повторов предыдущего символа.| +|?|Делает предыдущий символ необязательным.| +|{n,m}|Скобки. Искать не менее "n" и не более "m" повторов предыдущего символа.| +|(xyz)|Группа символов. Искать только символы xyz в указанном порядке.| +|||Чередование. Искать либо знаки до этого символа, либо знаки после символа.| +|\|Экранирование следующего символа. Позволяет искать специальные знаки:
[ ] ( ) { } . * + ? ^ $ \ |
|
+|^|Обозначает начало пользовательского ввода.|
+|$|Обозначает конец пользовательского ввода.|
+
+## 2.1 Точка
+
+Точка `.` — это простейший пример метасимвола. Метасимвол `.`
+находит любой отдельный символ. Точка не будет находить символы возврата каретки
+(CR) или перевода строки (LF). Например, регулярное выражение `.ar` обозначает
+"любой символ, за которым следуют буквы `a` и `r`".
+
++".ar" => The car parked in the garage. ++ +[Запустить регулярное выражение](https://regex101.com/r/xc9GkU/1) + +## 2.2 Набор символов. + +Набор символов, также называется классом символов. Для определения набора +символов используются квадратные скобки. Дефис используется для указания +диапазона символов. Порядок следования символов, заданный в квадратных скобках, +не важен. Например, регулярное выражение `[Tt]he` интерпретируется как +"заглавная `T` или строчная `t`, за которой следуют буквы `h` и `e`". + +
+"[Tt]he" => The car parked in the garage. ++ +[Запустить регулярное выражение](https://regex101.com/r/2ITLQ4/1) + +Точка внутри набора символов, внезапно, обозначает непосредственно точку как +символ. Регулярное выражение `ar[.]` обозначает строчную `a`, за которой следует +`r`, за которой следует `.` (символ точки). + +
+"ar[.]" => A garage is a good place to park a car. ++ +[Запустить регулярное выражение](https://regex101.com/r/wL3xtE/1) + +### 2.2.1 Отрицание набора символов + +Карет `^` обозначает начало строки, но если вы поставите его после открывающей +квадратной скобки, он инвертирует набор символов. Например, регулярное выражение +`[^c]ar` обозначает "любой символ, кроме `c`, за которым следуют буквы `a` и `r`". + +
+"[^c]ar" => The car parked in the garage. ++ +[Запустить регулярное выражение](https://regex101.com/r/nNNlq3/1) + +## 2.3 Повторения + +Символы `+`, `*` и `?` используются для обозначения того, сколько раз появляется +символ перед ними. Эти метасимволы ведут себя в разных ситуациях по-разному. + +### 2.3.1 Звёздочка + +Символ `*` обозначает ноль или более повторений предыдущего символа. Регулярное +выражение `a*` толкуется как "ноль или более повторений предыдущего строчного +символа `a`". Если же символ появляется после набора или класса символов, он +ищет повторения всего набора символов. Например, регулярное выражение `[a-z]*` +означает "любое количество строчных букв". + +
+"[a-z]*" => The car parked in the garage #21. ++ +[Запустить регулярное выражение](https://regex101.com/r/7m8me5/1) + +Символы можно комбинировать. Например, метасимвол `*` может использоваться с +метасимволом `.` для поиска строки с произвольным содержанием: `.*`. Символ `*` +может использоваться с символом пробела `\s`, чтобы искать строки с символами +пробела. Например, выражение `\s*cat\s*` означает: "ноль или более пробелов, за +которыми следует слово `cat`, за которым следует ноль или более символов +пробела". + +
+"\s*cat\s*" => The fat cat sat on the concatenation. ++ +[Запустить регулярное выражение](https://regex101.com/r/gGrwuz/1) + +### 2.3.2 Плюс + +Символ `+` соответствует одному или более повторению предыдущего символа. +Например, регулярное выражение `c.+t` интерпретируется так: "строчная `c`, за +которой следует по крайней мере один любой символ, следом за которым(и) идёт +символ `t`. Стоит уточнить, что в данном шаблоне, `t` является последним `t` в +строке. + +
+"c.+t" => The fat cat sat on the mat. ++ +[Запустить регулярное выражение](https://regex101.com/r/Dzf9Aa/1) + +### 2.3.3 Знак вопроса + +В регулярном выражении метасимвол `?` делает предыдущий символ необязательным. +Этот символ соответствует нулю или одному вхождению предыдущего символа. +Например, регулярное выражение `[T]?he` означает: "необязательная заглавная +буква `T`, за которой следуют символы `h` и `e`". + +
+"[T]he" => The car is parked in the garage. ++ +[Запустить регулярное выражение](https://regex101.com/r/cIg9zm/1) + +
+"[T]?he" => The car is parked in the garage. ++ +[Запустить регулярное выражение](https://regex101.com/r/kPpO2x/1) + +## 2.4 Фигурные скобки + +В фигурных скобках, которые также называются квантификаторами, указывается, +сколько раз символ или группа символов могут повторяться. Например, регулярное +выражение `[0-9]{2,3}` означает: "от 2 до 3 цифр в диапазоне от 0 до 9. + +
+"[0-9]{2,3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Запустить регулярное выражение](https://regex101.com/r/juM86s/1) + +Мы можем опустить второе число (цифру 3), тогда регулярное выражение `[0-9]{2,}` +будет значить "2 или более цифр". А если мы удалим запятую, регулярное выражение +`[0-9]{3}` будет искать ровно 3 цифры. + +
+"[0-9]{2,}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Запустить регулярное выражение](https://regex101.com/r/Gdy4w5/1) + +
+"[0-9]{3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Запустить регулярное выражение](https://regex101.com/r/Sivu30/1) + +## 2.5 Скобочные группы + +Скобочные группы — это группы подшаблонов, которые написаны в круглых скобках +`(...)`. Как мы уже говорили ранее, в регулярном выражении, квантификатор после +символа, ищет повторы символа перед квантификатором. Если мы поставим +квантификатор после скобочной группы, он будет искать повторы всей группы. К +примеру, регулярное выражение `(ab)*` соответствует нулю или более повторений +строки "ab". Мы также можем использовать метасимвол чередования `|` внутри +скобочной группы. Так, регулярное выражение `(c|g|p)ar` означает: "любая из +строчных букв `c`, `g` или `p`, за которой следуют буквы `a` и `r`". + +
+"(c|g|p)ar" => The car is parked in the garage. ++ +[Запустить регулярное выражение](https://regex101.com/r/tUxrBG/1) + +Обратите внимание, что скобочные группы не только находят, но и захватывают +символы для использования в языке программирования. Таким языком может быть +Python, JavaScript и практически любой язык, в котором регулярные выражения +можно использовать в параметрах функций. + +### 2.5.1 Незахватывающие скобочные группы + +Бывает так, что группу определить нужно, а вот захватывать её содержимое в +массив не требуется. Подобный трюк осуществляется при помощи специальной +комбинации `?:` в круглых скобках `(...)`. Так, регулярное выражение +`(?:c|g|p)ar` будет искать те же шаблоны, что и `(c|g|p)ar`, но группа захвата +при этом создана не будет. + +
+"(?:c|g|p)ar" => The car is parked in the garage. ++ +[Запустить регулярное выражение](https://regex101.com/r/Rm7Me8/1) + +Незахватывающие группы могут пригодиться, в ситуациях типа найти-и-заменить, или +вместе со скобочными группами, чтобы не засорять массив из захваченных данных +ненужными строками. Смотрите также [4. Опережающие и ретроспективные проверки](#4-опережающие-и-ретроспективные-проверки). + +## 2.6 Перечисление + +В регулярных выражениях вертикальная черта `|` используется для определения +перечисления (выбора). Перечисление похоже на оператор ИЛИ между выражениями. +Может создаться впечатление, что перечисление — это то же, что и набор символов. +Но набор символов работает на уровне конкретных символов, а перечисление +работает на уровне выражений. К примеру, регулярное выражение `(T|t)he|car` +значит: либо "заглавная `T` ИЛИ строчная `t`, с продолжением из `h` и `e`", либо +"строчная `c`, затем строчная `a`, за которой следует строчная `r`". Во входных +данных будут искаться оба шаблона, для удобства заключённые в кавычки. + +
+"(T|t)he|car" => The car is parked in the garage. ++ +[Запустить регулярное выражение](https://regex101.com/r/fBXyX0/1) + +## 2.7 Экранирование спецсимволов + +Обратный слэш `\` используется в регулярных выражениях для экранирования +следующего символа. Это позволяет формировать шаблоны с поиском специальных +символов, таких как `{ } [ ] / \ + * . $ ^ | ?`. Для использования спецсимвола в +шаблоне необходимо указать символ `\` перед ним. + +Например: символ `.` является специальным и соответствует любому знаку, кроме +символа новой строки. Чтобы найти точку во входных данных, воспользуется +выражением `(f|c|m)at\.?`: "строчный символ `f`, `c` или `m`, за которым следует +строчные буквы `a` и `t`, с необязательной `.` точкой в конце". + +
+"(f|c|m)at\.?" => The fat cat sat on the mat. ++ +[Запустить регулярное выражение](https://regex101.com/r/DOc5Nu/1) + +## 2.8 Якоря + +Якоря в регулярных выражениях используются для проверки, является ли +соответствующий символ первым или последним символом входной строки. Есть два +типа якорей: каретка `^` — проверяет, является ли соответствующий символ первым +символом в тексте, и доллар `$` — проверяет, является ли соответствующий символ +последним символом входной строки. + +### 2.8.1 Каретка + +Символ каретки `^` используется для проверки, является ли соответствующий символ +первым символом входной строки. Если мы применяем следующее регулярное выражение +`^a` ('a' является первым символом) для строки `abc`, совпадение будет +соответствовать букве `a`. Если же мы используем регулярное выражение `^b` на +той же строке, мы не получим совпадения, поскольку во входящей строке `abc` "b" +не является первым символом. Рассмотрим другое регулярное выражение: `^(T|t)he`, +оно значит "заглавная `T` или строчная `t` как первый символ, за которым следуют +буквы `h` и `e`". Cоответственно: + +
+"(T|t)he" => The car is parked in the garage. ++ +[Запустить регулярное выражение](https://regex101.com/r/5ljjgB/1) + +
+"^(T|t)he" => The car is parked in the garage. ++ +[Запустить регулярное выражение](https://regex101.com/r/jXrKne/1) + +### 2.8.2 Доллар + +Символ доллара `$` используется для проверки, является ли соответствующий символ +последним символом входной строки. Например, регулярное выражение `(at\.)$` +значит: "последовательность из строчной `a`, строчной `t`, точки `.`, находящая +в конце строки". Пример: + +
+"(at\.)" => The fat cat. sat. on the mat. ++ +[Запустить регулярное выражение](https://regex101.com/r/y4Au4D/1) + +
+"(at\.)$" => The fat cat. sat. on the mat. ++ +[Запустить регулярное выражение](https://regex101.com/r/t0AkOd/1) + +## 3. Наборы сокращений и диапазоны + +В регулярных выражениях есть сокращения для часто используемых наборов символов: + +|Сокращение|Описание| +|:----:|----| +|.|Любой символ, кроме символа перевода строки| +|\w|Английская буква либо цифра: `[a-zA-Z0-9_]`| +|\W|Любой символ, кроме английских букв и цифр: `[^\w]`| +|\d|Цифра: `[0-9]`| +|\D|Поиск всего, что не является цифрой: `[^\d]`| +|\s|Пробел либо символ начала строки: `[\t\n\f\r\p{Z}]`| +|\S|Любой символ, кроме пробела и символа начала строки: `[^\s]`| + +## 4. Опережающие и ретроспективные проверки + +Опережающие и ретроспективные проверки (lookbehind, lookahead) — это особый вид +***незахватывающих скобочных групп*** (находящих совпадения, но не добавляющих +в массив совпадений). Данные проверки используются, когда мы знаем, что шаблон +предшествует или сопровождается другим шаблоном. Например, мы хотим получить +цену в долларах `$` из следующей входной строки `$4.44 and $10.88`. Для этого +используем следующее регулярное выражение `(?<=\$)[0-9\.]*`, означающее +получение всех дробных (с точкой `.`) цифр, которым предшествует знак доллара +`$`. Существуют следующие виды проверок: + +|Символ|Описание| +|:----:|----| +|?=|Положительное опережающее условие| +|?!|Отрицательное опережающее условие| +|?<=|Положительное ретроспективное условие| +|? +"(T|t)he(?=\sfat)" => The fat cat sat on the mat. + + +[Запустить регулярное выражение](https://regex101.com/r/IDDARt/1) + +### 4.2 Отрицательное опережающее условие + +Отрицательное опережающее условие работает по обратному принципу: используется, +когда нам нужно получить все совпадения из входной строки, за которыми НЕ +следует определенный шаблон. Отрицательное опережающее условие определяется +таким же образом, как и положительное, с той лишь разницей, что вместо равенства +`=` мы ставим восклицательный знак `!` (логическое отрицание): `(?!...)`. +Пример: `(T|t)he(?!\sfat)` — ищем слова `The` или `the`, за которыми не следует +пробел и слово `fat`. + +
+"(T|t)he(?!\sfat)" => The fat cat sat on the mat. ++ +[Запустить регулярное выражение](https://regex101.com/r/V32Npg/1) + +### 4.3 Положительное ретроспективное условие + +Положительное ретроспективное условие используется чтобы найти все совпадения, +которым предшествует определенный шаблон. Условие определяется как `(?<=...)`. +Например, выражение `(?<=(T|t)he\s)(fat|mat)` означает: "найти все слова `fat` +или `mat` из входной строки, которым предшествует слово `The` или `the`". + +
+"(?<=(T|t)he\s)(fat|mat)" => The fat cat sat on the mat. ++ +[Запустить регулярное выражение](https://regex101.com/r/avH165/1) + +### 4.4 Отрицательное ретроспективное условие + +Отрицательное ретроспективное условие используется, чтобы найти все совпадения, +которым НЕ предшествует определенный шаблон. Условие определяется так: +`(? +"(?<!(T|t)he\s)(cat)" => The cat sat on cat. + + +[Запустить регулярное выражение](https://regex101.com/r/8Efx5G/1) + +## 5. Флаги + +Флаги, также называемые модификаторами, изменяют принцип работы регулярного +выражения. Эти флаги могут быть использованы в любом порядке или комбинации, и +являются неотъемлемой частью регулярных выражений. + +|Флаг|Описание| +|:----:|----| +|i|Поиск без учета регистра.| +|g|Глобальный поиск: искать все вхождения шаблона в тексте, а не только первое совпадение.| +|m|Мультистроковый поиск: якоря применяются к строкам, а не ко всему тексту.| + +### 5.1 Поиск без учета регистра + +Модификатор `i` используется для поиска без учета регистра. Например, регулярное +выражение `/The/gi` означает заглавную `T` следом строчные `h` и `e`. В конце +регулярного выражения флаг `i`, указывающий библиотеке регулярных выражений +игнорировать регистр символов. Дополнительно для поиска шаблона во всем входном +тексте, использован флаг `g`. + +
+"The" => The fat cat sat on the mat. ++ +[Запустить регулярное выражение](https://regex101.com/r/dpQyf9/1) + +
+"/The/gi" => The fat cat sat on the mat. ++ +[Запустить регулярное выражение](https://regex101.com/r/ahfiuh/1) + +### 5.2 Глобальный поиск + +Модификатор `g` используется для выполнения глобального сопоставления (найти все +совпадения, а не останавливаться после первого). К примеру, регулярное выражение +`/.(at)/g` означает: "любой символ (кроме начала новой строки), следом строчная +`a` и `t`". Благодаря флагу `g`, такое регулярное выражение найдёт все +совпадения во входной строке, а не остановится на первом (что является +поведением по умолчанию). + +
+"/.(at)/" => The fat cat sat on the mat. ++ +[Запустить регулярное выражение](https://regex101.com/r/jnk6gM/1) + +
+"/.(at)/g" => The fat cat sat on the mat. ++ +[Запустить регулярное выражение](https://regex101.com/r/dO1nef/1) + +### 5.3 Мультистроковый поиск + +Модификатор `m` используется для многострочного поиска. Как мы обсуждали ранее, +якоря `(^, $)` используются для проверки, является ли шаблон началом или концом +входных данных. Но если мы хотим, чтобы якоря работали в каждой строке, мы +используем флаг `m`. Например, регулярное выражение `/at(.)?$/gm` означает: +"строчная `a`, следом строчная `t` и необязательный любой символ (кроме начала +новой строки)". Благодаря флагу `m` библиотека регулярных выражений будет искать +данный шаблон в конце каждой строки в тексте. + +
+"/.at(.)?$/" => The fat + cat sat + on the mat. ++ +[Запустить регулярное выражение](https://regex101.com/r/hoGMkP/1) + +
+"/.at(.)?$/gm" => The fat + cat sat + on the mat. ++ +[Запустить регулярное выражение](https://regex101.com/r/E88WE2/1) + +## 6. Жадная и ленивая квантификация +По умолчанию регулярное выражение выполняет жадное сопоставление, то есть оно +будет искать самые длинные возможные совпадения. Мы можем использовать `?` для +ленивого поиска, который будет искать наименьшие возможные совпадения во входных +данных. + +
+"/(.*at)/" => The fat cat sat on the mat. ++ + +[Запустить регулярное выражение](https://regex101.com/r/AyAdgJ/1) + +
+"/(.*?at)/" => The fat cat sat on the mat. ++ + +[Запустить регулярное выражение](https://regex101.com/r/AyAdgJ/2) + + +## Участвуйте в жизни репозитория + +* Откройте пулл реквест с исправлением +* Обсуждайте идеи в issues +* Распространяйте знания и ссылку на репозиторий +* Приходите с отзывами к [](https://twitter.com/ziishaned) + +## Лицензия + +MIT © [Zeeshan Ahmad](https://twitter.com/ziishaned) diff --git a/translations/README-tr.md b/translations/README-tr.md new file mode 100644 index 00000000..113c6c3d --- /dev/null +++ b/translations/README-tr.md @@ -0,0 +1,638 @@ +
+
+
+
+
+
+
+
+
+"the" => The fat cat sat on the mat. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/dmRygT/1) + +`123` düzenli ifadesi `123` harf öbeğiyle eşleşir. Düzenli ifade birbiri ardına, +girilen harf öbeğindeki her karakter düzenli ifadenin içindeki her karakterle +karşılaştırılarak eşleştirilir. Düzenli ifadeler normal olarak büyük/küçük harfe +duyarlıdırlar, yani `The` düzenli ifadesi `the` harf öbeğiyle eşleşmez. + +
+"The" => The fat cat sat on the mat. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/1paXsy/1) + +## 2. Meta Karakterler + +Meta karakterler düzenli ifadelerin yapı taşlarıdırlar. Meta karakterler +kendileri için değil bunun yerine bazı özel yollarla yorumlanırlar. Bazı meta +karakterler özel anlamları vardır ve bunlar köşeli parantez içinde yazılırlar. + +Meta karakterler aşağıdaki gibidir: + +|Meta karakter|Açıklama| +|:----:|----| +|.|Satır başlangıcı hariç herhangi bir karakterle eşleşir.| +|[ ]|Köşeli parantezler arasında bulunan herhangi bir karakterle eşleşir.| +|[^ ]|Köşeli parantez içerisinde yer alan `^` işaretinden sonra girilen karakterler haricindeki karakterlerle eşleşir.| +|*|Kendisinden önce yazılan karakterin sıfır veya daha fazla tekrarı ile eşleşir.| +|+|Kendisinden önce yazılan karakterin bir veya daha fazla olan tekrarı ile eşleşir.| +|?|Kendisinden önce yazılan karakterin varlık durumunu opsiyonel kılar.| +|{n,m}|Kendisinden önce yazılan karakterin en az `n` en fazla `m` değeri kadar olmasını ifade eder.| +|(xyz)|Verilen sırayla `xyz` karakterleriyle eşleşir.| +||| Karakterden önce veya sonra verilen ifadelerin herhangi biriyle eşleşebilir. İfadeye Yada anlamı katar.| +|\|
[ ] ( ) { } . * + ? ^ $ \ |
özel karakterin aranmasını sağlar.|
+|^|Girilen verinin başlangıcını ifade eder.|
+|$|Girilen verinin sonunu ifade eder.|
+
+## 2.1 Nokta
+
+Nokta `.` meta karakterlerin en basit örneğidir. `.` meta karakteri satır
+başlangıcı hariç herhangi bir karakterle eşleşir. Örneğin, `.ar` düzenli
+ifadesinin anlamı: herhangi bir karakterin ardından `a` harfi ve `r` harfi
+gelir.
+
++".ar" => The car parked in the garage. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/xc9GkU/1) + +## 2.2 Karakter Takımı + +Karakter takımları ayrıca Karakter sınıfı olarak bilinir. Karakter takımlarını +belirtmek için köşeli ayraçlar kullanılır. Karakterin aralığını belirtmek için +bir karakter takımında tire kullanın. Köşeli parantezlerdeki karakter aralığının +sıralaması önemli değildir. + +Örneğin, `[Tt]he` düzenli ifadesinin anlamı: bir büyük `T` veya küçük `t` +harflerinin ardından sırasıyla `h` ve `e` harfi gelir. + +
+"[Tt]he" => The car parked in the garage. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/2ITLQ4/1) + +Bununla birlikte, bir karakter takımı içerisindeki bir periyot bir tam periyot +demektir. + +`ar[.]` düzenli ifadesinin anlamı: Küçük `a` karakteri ardından `r` harfi gelir, +ardından bir `.` karakteri gelir. + +
+"ar[.]" => A garage is a good place to park a car. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/wL3xtE/1) + +### 2.2.1 Dışlanmış Karakter Seti + +Genellikle, şapka `^` sembolü harf öbeğinin başlangıcını temsil eder, ama köşeli +parantez içinde kullanıldığında verilen karakter takımını hariç tutar. + +Örneğin, `[^c]ar` ifadesinin anlamı: `c` harfinden hariç herhangi bir harfin +ardından `a`, ardından `r` gelir. + +
+"[^c]ar" => The car parked in the garage. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/nNNlq3/1) + +## 2.3 Tekrarlar + +`+`, `*` ya da `?` meta karakterlerinden sonra bir alt desenin kaç defa tekrar +edebileceğini belirtmek için kullanılır. Bu meta karakterler farklı durumlarda +farklı davranırlar. + +### 2.3.1 Yıldız İşareti + +`*` sembolü, kendinden önce girilen eşlemenin sıfır veya daha fazla tekrarıyla +eşleşir. Ama bir karakter seti ya da sınıf sonrasına girildiğinde, tüm karakter +setinin tekrarlarını bulur. + +`a*` düzenli ifadesinin anlamı: `a` karakterinin sıfır veya daha fazla +tekrarları, `[a-z]*` düzenli ifadesinin anlamı ise bir satırdaki herhangi bir +sayıdaki küçük harfler anlamına gelir. + +
+"[a-z]*" => The car parked in the garage #21. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/7m8me5/1) + +`*` sembolü `.` meta karakteri ile `.*` karakterinin herhangi harf öbeğine +eşleştirmek için kullanılabilir. `*` sembolü boşluk karakteriyle `\s` bir harf +öbeğinde boşluk karakterlerini eşleştirmek için kullanılabilir. + +Örneğin, `\s*cat\s*` düzenli ifadesinin anlamı: sıfır veya daha fazla boşluk +ardından küçük `c` karakteri gelir, ardından küçük `a` karakteri gelir, ardından +küçük `t` karakteri gelir, ardından sıfır veya daha fazla boşluk gelir. + +
+"\s*cat\s*" => The fat cat sat on the concatenation. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/gGrwuz/1) + +### 2.3.2 Artı İşareti + +`+` sembolü, kendinden önce girilen eşlemenin bir veya daha fazla tekrarıyla +eşleşir. + +Örneğin, `c.+t` ifadesinin anlamı: küçük `c` harfi, ardından en az bir karakter +gelir, ardından küçük `t` karakteri gelir. Örnekte açıklamak gereken önemli +nokta: `t` harfi cümledeki son `t` harfi olacaktır. `c` ve `t` harfi arasında en +az bir karakter vardır. + +
+"c.+t" => The fat cat sat on the mat. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/Dzf9Aa/1) + +### 2.3.3 Soru İşareti + +Düzenli ifadelerde `?` meta karakterinden önce girilen karakteri opsiyonel +olarak tanımlar. Bu sembol önce gelen karakterin sıfır veya bir örneğiyle +eşleşir. + +Örneğin, `[T]?he` ifadesinin anlamı: opsiyonel büyük `T` harfi, ardından küçük +`h` karakteri gelir, ardından küçük `e` karakteri gelir. + +
+"[T]he" => The car is parked in the garage. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/cIg9zm/1) + +
+"[T]?he" => The car is parked in the garage. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/kPpO2x/1) + +## 2.4 Süslü Parantez + +Düzenli ifadelerde miktar belirliyiciler olarakda bilinen süslü parantezler, bir +karakterin veya karakter grubunun kaç defa tekrar edebileceğini belirtmek için +kullanılırlar. + +Örneğin, `[0-9]{2,3}` ifadesinin anlamı: 0 ile 9 aralığındaki karakterlerden, en +az 2 en fazla 3 defa ile eşleş. + +
+"[0-9]{2,3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/juM86s/1) + +İkinci numarayı boş bırakabiliriz. + +Örneğin, `[0-9]{2,}` ifadesinin anlamı: En az 2 veya daha fazla defa eşleş. +Düzenli ifadeden virgülü kaldırırsak `[0-9]{3}`: doğrudan 3 defa eşleşir. + +
+"[0-9]{2,}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/Gdy4w5/1) + +
+"[0-9]{3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/Sivu30/1) + +## 2.5 Karakter Grubu + +Karakter grubu parantezler içine yazılmış alt desenler grubudur. Daha önce +tasarım deseninde değindiğimiz gibi, bir karakterden önce bir miktar belirleyici +koyarsak önceki karakteri tekrar eder. Fakat miktar belirleyiciyi bir karakter +grubundan sonra koyarsak tüm karakter grubunu tekrarlar. + +Örneğin: `(ab)*` düzenli ifadesi "ab" karakterinin sıfır veya daha fazla +tekrarıyla eşleşir. + +Ayrıca karakter grubu içinde `|` meta karakterini kullanabiliriz. + +Örneğin, `(c|g|p)ar` düzenli ifadesinin anlamı: küçük `c`, `g` veya `p` +karakteri, ardından `a` karakteri, ardından `r` karakteri gelir. + +
+"(c|g|p)ar" => The car is parked in the garage. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/tUxrBG/1) + +Not olarak yakalanan gruplar yalnızca eşleşmez, ayrıca yakalanan karakterler ana dil içinde kullanılır.Bu ana dil Python, JavaScript ve neredeyse herhangi bir dilde düzenli ifadelerin fonksiyon tanımlamalarında olabilir. + +### 2.5.1 Karakter Grubu Olmayanlar + +Karakter grubu olmayan bir grup, karakterlerle eşleşen ancak grubu yakalayamayan bir yakalama grubudur. Karakter grubu olmayan bir grup parantez içinde`(...)` önce `?` ve ardından `:` ile gösterilir. Örneğin, `(?:c|g|p)ar` düzenli ifadesi, aynı karakterlerle eşleştiği ancak bir yakalama grubu oluşturmayacağı için `(c|g|p)ar` ifadesine benzer. + +
+"(?:c|g|p)ar" => The car is parked in the garage. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/Rm7Me8/1) + +Karakter grubu olmayanlar bul-ve-değiştir işlevselliğinde kullanıldığında veya karakter gruplarıyla karıştırıldığında, herhangi bir başka tür çıktı üretirken genel görünümü korumak için kullanışlı olabilir. +Ayrıca bakınız [4. Bakınmak](#4-bakınmak). + +## 2.6 Değişim + +Düzenli ifadede dik çizgi alternasyon(değişim, dönüşüm) tanımlamak için +kullanılır. Alternasyon birden fazla ifade arasındaki bir koşul gibidir. Şu an, +karakter grubu ve alternasyonun aynı şekilde çalıştığını düşünüyor +olabilirsiniz. Ama, Karakter grubu ve alternasyon arasındaki büyük fark karakter +grubu karakter düzeyinde çalışır ama alternasyon ifade düzeyinde çalışır. + +Örneğin, `(T|t)he|car` düzenli ifadesinin anlamı: Büyük `T` ya da küçük `t` +karakteri, ardından küçük `h` karakteri, ardından küçük `e` ya da `c` karakteri, +ardından küçük `a`, ardından küçük `r` karakteri gelir. + +
+"(T|t)he|car" => The car is parked in the garage. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/fBXyX0/1) + +## 2.7 Özel Karakter Hariç Tutma + +`\` işareti sonraki karakteri hariç tutmak için kullanılır. Bu bir semboülü +ayrılmış karakterlerde `{ } [ ] / \ + * . $ ^ | ?` dahil olmak üzere eşleşen bir +karakter olarak belirtmemizi sağlar. Bir özel karakteri eşleşen bir karakter +olarak kullanmak için önüne `\` işareti getirin. + +Örneğin, `.` düzenli ifadesi yeni satır hariç herhangi bir karakteri eşleştirmek +için kullanılır. Bir harf öbeği içinde nokta `.` karakterini yakalamak için `.` +ayrılmış karakterini hariç tutmamız gerekir. Bunun için nokta önüne `\` +işaretini koymamız gereklidir. + +`(f|c|m)at\.?` düzenli ifadesinin anlamı: küçük `f`, `c`ya da `m` harfi, +ardından küçük `a` harfi, ardından küçük `t` harfi, ardından opsiyonel `.` +karakteri gelir. + +
+"(f|c|m)at\.?" => The fat cat sat on the mat. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/DOc5Nu/1) + +## 2.8 Sabitleyiciler + +Düzenli ifadelerde, eşleşen sembolün girilen harf öbeğinin başlangıç sembolü +veya bitiş sembolü olup olmadığını kontrol etmek için sabitleyicileri +kullanırız. Sabitleyiciler iki çeşittir: İlk çeşit, eşleşen karakterin girişin +ilk karakteri olup olmadığını kontrol eden şapka `^` karakteri, ikinci çeşit ise +eşleşen karakterin girişin son karakteri olup olmadığını kontrol eden dolar `$` +karakteridir. + +### 2.8.1 Şapka İşareti + +Şapka `^` işareti eşleşen karakterin giriş harf öbeğinin ilk karakteri olup +olmadığını kontrol etmek için kullanılır. Eğer `^a` düzenli ifadesini `abc` harf +öbeğine uygularsak `a` ile eşleşir. Ama `^b` ifadesini uygularsak bir eşleşme +bulamayız. Bunun nedeni `abc` harf öbeğinde `b` karakterinin başlangıç karakteri +olmamasıdır. + +Bir başka örnek üzerinden ilerlersek, + +`^(T|t)he` düzenli ifadesinin anlamı: büyük `T` ya da `t` karakteri giriş harf +öbeğinin ilk karakteri olmak üzere, ardından küçük `h`, ardından küçük `e` +karakteri gelir. + +
+"(T|t)he" => The car is parked in the garage. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/5ljjgB/1) + +
+"^(T|t)he" => The car is parked in the garage. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/jXrKne/1) + +### 2.8.2 Dolar İşareti + +Dolar `$` işareti eşleşen karakterin giriş harf öbeğinin son karakteri olup +olmadığını kontrol etmek için kullanılır. + +Örneğin, `(at\.)$` ifadesinin anlamı: küçük bir `a` karakteri, ardından küçük +bir `t` karakteri, ardıdan nokta `.` karakteri gelir ve bu eşleşme harf öbeğinin +sonunda olmalıdır. + +
+"(at\.)" => The fat cat. sat. on the mat. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/y4Au4D/1) + +
+"(at\.)$" => The fat cat. sat. on the mat. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/t0AkOd/1) + +## 3. Kısaltma Karakter Takımları + +Regex, sık olarak kullanılan düzenli ifadeler için özel karakter setleri ve +kısaltmalar sağlar. + +Kullanılan karakter setlerinin kısaltmaları aşağıdaki gibidir: + +|Kısaltma|Açıklama| +|:----:|----| +|.|Satır başı hariç herhangi bir karakter| +|\w|Alfanumerik karakterlerle eşleşir: `[a-zA-Z0-9_]`| +|\W|Alfanumerik olmayan karakterlerle eşleşir: `[^\w]`| +|\d|Rakamlarla eşlelir: `[0-9]`| +|\D|Rakam olmayan karakterlerle eşleşir: `[^\d]`| +|\s|Boşluk karakteri ile eşleşir: `[\t\n\f\r\p{Z}]`| +|\S|Boşluk karakteri olmayan karakterlerle eşleşir: `[^\s]`| + +## 4. Bakınmak + +Bakınma sembolleri, bir ifade öncesinde veya sonrasında başka bir ifademiz +olduğunda kullanılırlar. + +Örneğin, `$4.44 ve $10.88` girişlerinden `$` karakteri önündeki tüm sayıları +almak istiyoruz, bu durumda `(?<=\$)[0-9\.]*` ifadesini kullanırız. + +`(?<=\$)[0-9\.]*` ifadesinin anlamı: `.` karakterini içeren ve `$` karakteriyle +devam eden tüm sayıları al demektir. + +Düzenli ifadelerde kullanılan bakınma sembolleri aşadaki gibidir: + +|Sembol|Açıklama| +|:----:|----| +|?=|Pozitif İleri Bakınma (Verdiğimiz ifade sonrası arar ve `eşleşme varsa` sonuç döndürür.)| +|?!|Negatif İleri Bakınma (Verdiğimiz ifade sonrası arar ve `eşleşme yoksa` sonuç döndürür.)| +|?<=|Pozitif Geri Bakınma (Verdiğimiz ifade öncesini arar ve `eşleşme varsa` sonuç döndürür.)| +|? +"[T|t]he(?=\sfat)" => The fat cat sat on the mat. + + +[Düzenli ifadeyi test edin](https://regex101.com/r/IDDARt/1) + +### 4.2 Negatif İleri Bakınma + +Negatif ileri bakınma sembolü positive lookahead tersine, verdiğimiz desenle devam +etmemesi durumunda eşleşir. Bu sembol pozitif ileri bakınma gibi tanımlanır ama `=` +işareti yerine `!` kullanılır. + +`[T|t]he(?!\sfat)` ifadesinin anlamı: opsiyonel küçük bir `t` ya da büyük `T` +harfi, ardından `h` harfi gelir, ardından `e` harfi gelir, ardından öncesinde +boşluk olan bir `fat` öbeği olmamalıdır. + + +
+"[T|t]he(?!\sfat)" => The fat cat sat on the mat. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/V32Npg/1) + +### 4.3 Pozitif Geri Bakınma + +Pozitif geri bakınma, belirli bir desenden önceki eşleşmeleri almak için +kullanılır. `(?<=...)` ile gösterilir. + +Örneğin, `(?<=[T|t]he\s)(fat|mat)` ifadesinin anlamı: Öncesinde `The` veya `the` +öbekleri olan tüm `fat` veya `mat` öbeklerini getir. + +
+"(?<=[T|t]he\s)(fat|mat)" => The fat cat sat on the mat. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/avH165/1) + +### 4.4 Negatif Geri Bakınma + +Negatif geri bakınma, belirli bir desenden önce olmayan eşleşmeleri almak için +kullanılır. `(?<=!..)` ile gösterilir. + +Örneğin, `(? +"(?<![T|t]he\s)(cat)" => The cat sat on cat. + + +[Düzenli ifadeyi test edin](https://regex101.com/r/8Efx5G/1) + +## 5. İşaretler + +İşaretler ayrıca düzenleyiciler olarak bilinirler, çünkü bir düzenli +ifadenin çıktısını düzenlerler. Bu işaretler herhangi bir sırada veya +kombinasyonda kullanılabilirler ve Düzenli İfadelerin ayrılmaz bir +parçasıdırlar. + +|İşaret|Açıklama| +|:----:|----| +|i|Büyük küçük harf duyarlılık: Eşleştirmeleri küçük/büyük harfe karşı duyarsız yapar.| +|g|Genel Arama: Girilen harf öbeği boyunca bir desen arar.| +|m|Çok satırlı: Sabitleyici meta karakteri her satırda çalışır.| + +### 5.1 Büyük/Küçük Harf Duyarlılığı + +`i` işaretleyicisi büyük/küçük harfe duyarsız eşleştirme yapmak için kullanılır. + +Örneğin, `/The/gi` ifadesi: büyük `T` harfi, ardından küçük `h` harfi, ardından +küçük `e` harfi gelir. ifadenin sonunda yer alan `i` işareti büyük-küçük harfe +karşı duyarsız olması gerektiğini belirtir. Ayrıca `g` işaretinide +kullandığımızı görebilirsiniz, tüm text içinde bu aramayı yapmak istediğimiz +için `g` işaretini ayrıca belirtiyoruz. + +
+"The" => The fat cat sat on the mat. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/dpQyf9/1) + +
+"/The/gi" => The fat cat sat on the mat. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/ahfiuh/1) + +### 5.2 Genel Arama + +`g` işareti bir giriş içinde eşleşen tüm varsayonları bulmak için kullanılır. +`g` işareti kullanılmazsa ilk eşleşme bulunduktan sonra arama sona erer. + +
+"/.(at)/" => The fat cat sat on the mat. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/jnk6gM/1) + +
+"/.(at)/g" => The fat cat sat on the mat. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/dO1nef/1) + +### 5.3 Çok Satırlı + +`m` işareti çok satırlı bir eşleşme bulmak için kullanılır. Daha önce +sabitleyicilerde gördüğümüz gibi `(^, $)` sembolleri aradığımız desenin harf +öbeğinin başında veya sonunda olup olmadığını kontrol etmemiz için kullanılır. +Bu sabitleyicilerin tüm satırlarda çalışması için `m` işaretini kullanırız. + +Örneğin, `/at(.)?$/gm` ifadesinin anlamı: küçük `a` harfi, ardından küçük `t` +harfi gelir, ardından opsiyonel olarak yeni satır hariç herhangi birşey +gelebilir. `m` işaretini kullandığımız için bir girişin her satırının sonunda +eşleştirir. + +
+"/.at(.)?$/" => The fat + cat sat + on the mat. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/hoGMkP/1) + +
+"/.at(.)?$/gm" => The fat + cat sat + on the mat. ++ +[Düzenli ifadeyi test edin](https://regex101.com/r/E88WE2/1) + +## 6. Açgözlü vs Tembel Eşleştirme + +Varsayılan olarak, bir düzenli ifade açgözlü bir eşleştirme yapacaktır, bu da eşleşmenin mümkün olduğu kadar çok olacağı anlamına gelir. Tembel bir şekilde eşleştirmek için `?` kullanabiliriz, bu da eşleşme olabildiğince kısa olacaktır. +
+"/(.*at)/" => The fat cat sat on the mat.+ + +[Düzenli ifadeyi test edin](https://regex101.com/r/AyAdgJ/1) + +
+"/(.*?at)/" => The fat cat sat on the mat.+ + +[Düzenli ifadeyi test edin](https://regex101.com/r/AyAdgJ/2) + +## Katkı Sağla + +* Hataları Raporla +* İyileştirmeler iç Pull Request aç +* Paylaş +* Geri bildirim için [](https://twitter.com/ziishaned)'den eriş + +## Lisans + +MIT © [Zeeshan Ahmad](https://twitter.com/ziishaned) diff --git a/translations/README-vn.md b/translations/README-vn.md new file mode 100644 index 00000000..3a5b2908 --- /dev/null +++ b/translations/README-vn.md @@ -0,0 +1,566 @@ +
+
+
+
+
+
+
+
+
+"the" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/dmRygT/1) + +Biểu thức chính quy `123` khớp với chuỗi `123`. Biểu thức chính quy được khớp với chuỗi đầu vào bằng cách so sánh từng ký tự trong biểu thức chính quy với từng ký tự trong chuỗi đầu vào, lần lượt từng ký tự. Biểu thức chính quy thường phân biệt chữ hoa chữ thường nên biểu thức chính quy `The` sẽ không khớp với chuỗi `the`. + +
+"The" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/1paXsy/1) + +## 2. Meta Characters + +Các ký tự `meta` là các khối xây dựng của các biểu thức chính quy. Các ký tự `meta` không biểu diễn chính nó mà thay vào đó được diễn giải theo một cách đặc biệt nào đó. Một số ký tự `meta` có ý nghĩa đặc biệt và được viết bên trong dấu ngoặc vuông. Các ký tự meta như sau: + +|Meta character|Description| +|:----:|----| +|.|Khớp với tất cả các kí tự trừ dấu xuống dòng.| +|[ ]|Lớp kí tự. Khớp với bất kỳ ký tự nào nằm giữa dấu ngoặc vuông.| +|[^ ]|Lớp kí tự phủ định. Khớp với bất kỳ ký tự nào không có trong dấu ngoặc vuông.| +|*|Khớp 0 hoặc nhiều lần lặp lại của kí tự trước.| +|+|Khớp 1 hoặc nhiều lần lặp lại của kí tự trước.| +|?|Làm cho kí tự trước tùy chọn.| +|{n,m}|Braces. Khớp ít nhất là "n" nhưng không nhiều hơn "m" lặp lại của kí tự trước.| +|(xyz)|Nhóm kí tự. Khớp các ký tự xyz theo thứ tự chính xác đó.| +|||Thay thế. Khớp các ký tự trước hoặc ký tự sau ký hiệu.| +|\|Thoát khỏi kí tự tiếp theo. Điều này cho phép bạn khớp các ký tự dành riêng
[ ] ( ) { } . * + ? ^ $ \ |
|
+|^|Khớp với sự bắt đầu của đầu vào.|
+|$|Khớp với kết thúc đầu vào.|
+
+## 2.1 Full stop
+
+
+Full stop `.` là ví dụ đơn giản nhất về ký tự meta. Kí tự meta `.`
+khớp với bất kì kí tự nào. Nó sẽ không khớp kí tự trả về (return) hoặc xuống dòng (newline)
+
+Ví dụ, biểu thức chính quy `.ar` có ý nghĩa: bất kỳ ký tự nào, theo sau là chữ `a`, tiếp theo là chữ `r`.
+
++".ar" => The car parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/xc9GkU/1) + +## 2.2 Character set + +Bộ ký tự cũng được gọi là lớp kí tự. Dấu ngoặc vuông được sử dụng để chỉ định bộ ký tự. Sử dụng dấu gạch nối bên trong bộ ký tự để chỉ định phạm vi của các ký tự. Thứ tự của phạm vi ký tự trong dấu ngoặc vuông không quan trọng. + +Ví dụ: biểu thức chính quy `[Tt]he` có nghĩa là: chữ hoa `T` hoặc chữ thường `t`, theo sau là chữ `h`, tiếp theo là chữ `e`. + +
+"[Tt]he" => The car parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/2ITLQ4/1) + + +Tuy nhiên, khoảng thời gian bên trong một bộ ký tự có nghĩa là một khoảng thời gian theo nghĩa đen. Biểu thức chính quy `ar[.]` Có nghĩa là: ký tự chữ thường `a`, theo sau là chữ `r`, theo sau là kí tự `.` . + +
+"ar[.]" => A garage is a good place to park a car. ++ +[Test the regular expression](https://regex101.com/r/wL3xtE/1) + +### 2.2.1 Negated character set + +Nói chung, biểu tượng dấu mũ biểu thị sự bắt đầu của chuỗi, nhưng khi nó được gõ sau dấu ngoặc vuông mở, nó sẽ phủ định bộ ký tự. Ví dụ: biểu thức chính quy `[^ c]ar` có nghĩa là: bất kỳ ký tự nào ngoại trừ `c`, theo sau là ký tự `a`, theo sau là chữ `r`. + +
+"[^c]ar" => The car parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/nNNlq3/1) + + + + +## 2.3 Repetitions + +Theo dõi các ký tự meta, `+`, `*` hoặc `?` được sử dụng để xác định số lần mô hình con (subpattern) có thể xảy ra. Những kí tự meta này hành động khác nhau trong các tình huống khác nhau. + + +### 2.3.1 The Star + +Biểu tượng `*` khớp 0 hoặc nhiều lần lặp lại của trình so khớp trước. Biểu thức chính quy `a*` có nghĩa là: 0 hoặc nhiều lần lặp lại ký tự chữ thường trước `a`. Nhưng nếu nó xuất hiện sau một bộ ký tự hoặc lớp thì nó sẽ tìm thấy sự lặp lại của toàn bộ bộ ký tự. Ví dụ: biểu thức chính quy `[a-z]*` có nghĩa là: bất kỳ số lượng chữ cái viết thường trong một hàng. + +
+"[a-z]*" => The car parked in the garage #21. ++ +[Test the regular expression](https://regex101.com/r/7m8me5/1) + +Biểu tượng `*` có thể được sử dụng với ký tự meta. để khớp với bất kỳ chuỗi ký tự nào `.*` . Biểu tượng `*` có thể được sử dụng với ký tự khoảng trắng `\s` để khớp với một chuỗi các ký tự khoảng trắng. + +Ví dụ: biểu thức `\s*cat\s*` có nghĩa là: không hoặc nhiều khoảng trắng, theo sau là ký tự chữ thường `c`, theo sau là ký tự chữ thường `a`, theo sau là ký tự chữ thường `t`, tiếp theo là 0 hoặc nhiều khoảng trắng. + + +
+"\s*cat\s*" => The fat cat sat on the concatenation. ++ +[Test the regular expression](https://regex101.com/r/gGrwuz/1) + + + + +### 2.3.2 The Plus + + +Biểu tượng `+` khớp với một hoặc nhiều lần lặp lại của ký tự trước. + +Ví dụ: biểu thức chính quy `c.+t` có nghĩa là: chữ thường chữ `c`, theo sau là ít nhất một ký tự, tiếp theo là ký tự chữ thường `t`. Nó cần phải được làm rõ rằng `t` là `t` cuối cùng trong câu. + + +
+"c.+t" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/Dzf9Aa/1) + +### 2.3.3 The Question Mark + +Trong biểu thức chính quy các ký tự meta `?` làm cho ký tự trước là một tùy chọn. Biểu tượng này khớp với 0 hoặc một thể hiện (instance ) của ký tự trước. Ví dụ: biểu thức chính quy `[T]?he` có nghĩa là: Tùy chọn chữ hoa chữ `T`, theo sau là ký tự chữ thường `h`, tiếp theo là ký tự chữ thường `e`. + +
+"[T]he" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/cIg9zm/1) + +
+"[T]?he" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/kPpO2x/1) + + +## 2.4 Braces + + +Trong các dấu ngoặc nhọn thông thường còn được gọi là bộ định lượng được sử dụng để chỉ định số lần mà một ký tự hoặc một nhóm ký tự có thể được lặp lại. Ví dụ: biểu thức chính quy `[0-9]{2,3}` có nghĩa là: Ghép ít nhất 2 chữ số nhưng không quá 3 (ký tự trong phạm vi từ 0 đến 9). + + +
+"[0-9]{2,3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Test the regular expression](https://regex101.com/r/juM86s/1) + + +Chúng ta có thể bỏ qua số thứ hai. Ví dụ: biểu thức chính quy `[0-9]{2,}` có nghĩa là: Ghép 2 chữ số trở lên. Nếu chúng tôi cũng xóa dấu phẩy, biểu thức chính quy `[0-9]{3}` có nghĩa là: Ghép chính xác 3 chữ số. + +
+"[0-9]{2,}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Test the regular expression](https://regex101.com/r/Gdy4w5/1) + +
+"[0-9]{3}" => The number was 9.9997 but we rounded it off to 10.0. ++ +[Test the regular expression](https://regex101.com/r/Sivu30/1) + + +## 2.5 Capturing Group + +Một nhóm capturing là một nhóm các mẫu con được viết bên trong Dấu ngoặc đơn `(...)`. Giống như chúng ta đã thảo luận trước đó trong biểu thức chính quy nếu chúng ta đặt một bộ định lượng sau một ký tự thì nó sẽ lặp lại ký tự trước. Nhưng nếu chúng ta đặt bộ định lượng sau một nhóm capturing thì nó lặp lại toàn bộ nhóm capturing. Ví dụ: biểu thức chính quy `(ab)*` khớp với 0 hoặc nhiều lần lặp lại của ký tự "ab". Chúng ta cũng có thể sử dụng luân phiên `|` kí tự meta trong nhóm capturing. Ví dụ: biểu thức chính quy `(c|g|p)ar` có nghĩa là: ký tự chữ thường `c`, `g` hoặc `p`, theo sau là ký tự `a`, tiếp theo là ký tự `r`. + + + +
+"(c|g|p)ar" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/tUxrBG/1) + + +Lưu ý rằng các nhóm capturing không chỉ khớp mà còn capturing các ký tự để sử dụng trong ngôn ngữ gốc. Ngôn ngữ gốc có thể là python hoặc javascript hoặc hầu như bất kỳ ngôn ngữ nào thực hiện các biểu thức chính quy trong định nghĩa hàm. + + +### 2.5.1 Non-capturing group + +Nhóm không capturing là nhóm capturing chỉ khớp với các ký tự, nhưng không capturing được nhóm. Một nhóm không capturing được ký hiệu là `?` theo sau là `:` trong ngoặc đơn `(...)`. + +Ví dụ: biểu thức chính quy `(?:c|g|p)ar` tương tự như `(c|g|p)ar` ở chỗ nó khớp với các ký tự giống nhau nhưng sẽ không tạo nhóm capturing. + +
+"(?:c|g|p)ar" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/Rm7Me8/1) + +Các nhóm không capturing có thể có ích khi được sử dụng trong chức năng tìm và thay thế hoặc khi trộn với các nhóm capturing để giữ tổng quan khi sản xuất bất kỳ loại đầu ra nào khác. Xem thêm [4. Lookaround](#4-lookaround). + + +## 2.6 Alternation + +Trong một biểu thức chính quy, thanh dọc `|` được sử dụng để xác định xen kẽ. Sự xen kẽ giống như một câu lệnh OR giữa nhiều biểu thức. Bây giờ, bạn có thể nghĩ rằng bộ ký tự và luân phiên hoạt động theo cùng một cách. Nhưng sự khác biệt lớn giữa bộ ký tự và xen kẽ là bộ ký tự hoạt động ở cấp độ ký tự nhưng xen kẽ hoạt động ở cấp độ biểu thức. + +Ví dụ: biểu thức chính quy `(T|t)he|car` có nghĩa là: hoặc (ký tự chữ `T` hoặc chữ thường `t`, theo sau là ký tự chữ thường `h`, tiếp theo là ký tự chữ thường `e`) OR (ký tự chữ thường `c`, tiếp theo là ký tự chữ thường `a`, theo sau bằng ký tự viết thường `r`). Lưu ý rằng tôi đặt dấu ngoặc đơn cho rõ ràng, để cho thấy rằng một trong hai biểu thức trong ngoặc đơn có thể được đáp ứng và nó sẽ khớp. + +
+"(T|t)he|car" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/fBXyX0/1) + +## 2.7 Escaping special character + + +Dấu gạch chéo ngược `\` được sử dụng trong biểu thức chính quy để thoát ký tự tiếp theo. Điều này cho phép chúng tôi chỉ định một biểu tượng là một ký tự phù hợp bao gồm các ký tự dành riêng `{} [] / \ *. $ ^ | ?` . Để sử dụng một ký tự đặc biệt, ta dùng `\` làm ký tự trùng khớp trước kí tự ta muốn dùng. + +Ví dụ, biểu thức chính quy `.` được sử dụng để khớp với bất kỳ ký tự nào ngoại trừ dòng mới. Bây giờ để phù hợp `.` trong một chuỗi đầu vào, biểu thức chính quy `(f|c|m)at\.?` có nghĩa là: chữ thường `f`, `c` hoặc `m`, theo sau là ký tự chữ thường `a`, tiếp theo là chữ thường chữ `t`, theo sau là tùy chọn `.` tính cách. + + +
+"(f|c|m)at\.?" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/DOc5Nu/1) + + +## 2.8 Anchors + + +Trong các biểu thức chính quy, chúng tôi sử dụng các anchors để kiểm tra xem biểu tượng phù hợp là biểu tượng bắt đầu hay biểu tượng kết thúc của chuỗi đầu vào. Các anchors có hai loại: Loại thứ nhất là Caret `^` kiểm tra xem ký tự khớp có phải là ký tự bắt đầu của đầu vào không và loại thứ hai là Dollar `$` kiểm tra xem ký tự khớp có phải là ký tự cuối cùng của chuỗi đầu vào không. + + + + +### 2.8.1 Caret + + +Biểu tượng Caret `^` được sử dụng để kiểm tra xem ký tự khớp có phải là ký tự đầu tiên của chuỗi đầu vào không. Nếu chúng ta áp dụng biểu thức chính quy sau `^a` ( nếu a là ký hiệu bắt đầu) cho chuỗi đầu vào `abc` thì nó khớp với `a`. Nhưng nếu chúng ta áp dụng biểu thức chính quy `^b` trên chuỗi đầu vào ở trên thì nó không khớp với bất cứ thứ gì. Bởi vì trong chuỗi đầu vào `abc` "b" không phải là ký hiệu bắt đầu. Chúng ta hãy xem một biểu thức chính quy khác `^(T|t)he` có nghĩa là: ký tự chữ hoa `T` hoặc ký tự chữ thường `t` là ký hiệu bắt đầu của chuỗi đầu vào, tiếp theo là ký tự chữ thường `h`, tiếp theo là ký tự chữ thường `e`. + + +
+"(T|t)he" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/5ljjgB/1) + +
+"^(T|t)he" => The car is parked in the garage. ++ +[Test the regular expression](https://regex101.com/r/jXrKne/1) + +### 2.8.2 Dollar + + +Biểu tượng Dollar `$` được sử dụng để kiểm tra xem ký tự khớp có phải là ký tự cuối cùng của chuỗi đầu vào không. Ví dụ: biểu thức chính quy `(at\.)$` có nghĩa là: ký tự chữ thường `a`, theo sau là ký tự chữ thường `t`, theo sau là `.` ký tự và bộ so khớp phải là cuối chuỗi. + + + +
+"(at\.)" => The fat cat. sat. on the mat. ++ +[Test the regular expression](https://regex101.com/r/y4Au4D/1) + +
+"(at\.)$" => The fat cat. sat. on the mat. ++ +[Test the regular expression](https://regex101.com/r/t0AkOd/1) + +## 3. Shorthand Character Sets + + + +Biểu thức chính quy cung cấp các shorthand cho các bộ ký tự thường được sử dụng, cung cấp các shorthand thuận tiện cho các biểu thức thông thường được sử dụng. Các bộ ký tự shorthand như sau: + + +|Shorthand|Description| +|:----:|----| +|.| Bất kỳ kí tự nào ngoại trừ dòng mới| +|\w|Khớp các ký tự chữ và số: `[a-zA-Z0-9_]`| +|\W|Khớp các ký tự không phải chữ và số: `[^\w]`| +|\d|khớp với số trong khoảng: `[0-9]`| +|\D|Khớp không có chữ số: `[^\d]`| +|\s|Khớp các ký tự khoảng trắng: `[\t\n\f\r\p{Z}]`| +|\S|Khớp với ký tự không phải khoảng trắng: `[^\s]`| + +## 4. Lookaround + +Lookbehind và lookahead (còn được gọi là lookaround) là các loại nhóm ***không capturing*** cụ thể (Được sử dụng để khớp với mẫu nhưng không được bao gồm trong danh sách phù hợp). `Lookarounds` sử dụng khi chúng ta có điều kiện mẫu này được đi trước hoặc theo sau bởi một mẫu khác. + +Ví dụ: chúng tôi muốn nhận tất cả các số có trước ký tự `$` từ chuỗi đầu vào sau `$4,44 và $10,88`. Chúng tôi sẽ sử dụng biểu thức chính quy sau `(?<=\$)[0-9\.]*` có nghĩa là: lấy tất cả các số có chứa `.` ký tự và đứng trước ký tự `$`. Sau đây là những cái nhìn được sử dụng trong các biểu thức thông thường: + +|Kí hiệu|Mô tả| +|:----:|----| +|?=|Positive Lookahead| +|?!|Negative Lookahead| +|?<=|Positive Lookbehind| +|? +"(T|t)he(?=\sfat)" => The fat cat sat on the mat. + + +[Test the regular expression](https://regex101.com/r/IDDARt/1) + +### 4.2 Negative Lookahead + + +`Negative lookahead` được sử dụng khi chúng ta cần lấy tất cả các kết quả khớp từ chuỗi đầu vào không được theo sau bởi một mẫu. `Negative lookahead` được định nghĩa giống như chúng ta định nghĩa `positive lookahead` nhưng sự khác biệt duy nhất là thay vì bằng ký tự `=` chúng ta sử dụng kí tự phủ định `!` tức là `(?! ...)`. + +Chúng ta hãy xem biểu thức chính quy sau đây: `(T|t)he(?!\sfat)` có nghĩa là: lấy tất cả các từ `The` hoặc `the` từ chuỗi đầu vào không được đứng trước bởi từ `fat` trước một ký tự khoảng trắng. + +
+"(T|t)he(?!\sfat)" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/V32Npg/1) + +### 4.3 Positive Lookbehind + +`Positive lookbehind` được sử dụng để có được tất cả mẫu khớp cái mà theo sau bởi một mẫu cụ thể. `Positive lookbehind` được biểu thị bởi `(?<=...)`. + +Ví dụ: biểu thức chính quy `(?<=(T|t)he\s)(fat|mat)` có nghĩa là: lấy tất cả các từ `fat` hoặc `mat` từ chuỗi đầu vào, cái mà sau từ `The` hoặc `the`. + + + +
+"(?<=(T|t)he\s)(fat|mat)" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/avH165/1) + +### 4.4 Negative Lookbehind + + +`Negative lookbehind` được sử dụng để có được tất cả các từ khớp không có trước một mẫu cụ thể. `Negative lookbehind` được ký hiệu là `(? +"(?<!(T|t)he\s)(cat)" => The cat sat on cat. + + +[Test the regular expression](https://regex101.com/r/8Efx5G/1) + +## 5. Flags + + +Cờ (flags) cũng được gọi là bổ nghĩa (modifiers) vì chúng sửa đổi đầu ra của biểu thức chính quy. Các cờ này có thể được sử dụng theo bất kỳ thứ tự hoặc kết hợp nào và là một phần không thể thiếu của RegExp. + + + +|Cờ|Mô tả| +|:------:|----| +|i|Case insensitive: Đặt khớp với mẫu không phân biệt chữ hoa chữ thường.| +|g|Global Search: Tìm kiếm một mẫu trong suốt chuỗi đầu vào.| +|m|Multiline: ký tự Anchor meta hoạt động trên mỗi dòng.| + +### 5.1 Case Insensitive + + +Công cụ sửa đổi `i` được sử dụng để thực hiện khớp không phân biệt chữ hoa chữ thường. + +Ví dụ: biểu thức chính quy `/The/gi` có nghĩa là: chữ hoa chữ `T`, theo sau là ký tự chữ thường `h`, tiếp theo là ký tự `e`. Và ở cuối biểu thức chính quy, cờ `i` báo cho công cụ biểu thức chính quy bỏ qua trường hợp này. Như bạn có thể thấy, chúng tôi cũng đã cung cấp cờ `g` vì chúng tôi muốn tìm kiếm mẫu trong toàn bộ chuỗi đầu vào. + +
+"The" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/dpQyf9/1) + +
+"/The/gi" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/ahfiuh/1) + +### 5.2 Global search + + +Công cụ sửa đổi `g` được sử dụng để thực hiện khớp toàn cầu (tìm tất cả các từ có thể khớp thay vì dừng sau lần khớp đầu tiên). + +Ví dụ: biểu thức chính quy `/.(at)/g` có nghĩa là: bất kỳ ký tự nào ngoại trừ dòng mới, theo sau là ký tự chữ thường `a`, tiếp theo là ký tự chữ thường `t`. Vì chúng tôi đã cung cấp cờ `g` ở cuối biểu thức chính quy nên bây giờ nó sẽ tìm thấy tất cả các kết quả khớp trong chuỗi đầu vào, không chỉ là đầu tiên (là hành vi mặc định). + +
+"/.(at)/" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/jnk6gM/1) + +
+"/.(at)/g" => The fat cat sat on the mat. ++ +[Test the regular expression](https://regex101.com/r/dO1nef/1) + +### 5.3 Multiline + + +Công cụ sửa đổi `m` được sử dụng để thực hiện khớp nhiều dòng. Như chúng ta đã thảo luận về các anchors `(^, $)` trước đó, được sử dụng để kiểm tra xem mẫu là phần đầu của phần đầu vào hay phần cuối của chuỗi đầu vào. Nhưng nếu chúng ta muốn các anchors hoạt động trên mỗi dòng, chúng ta sử dụng cờ `m`. + +Ví dụ: biểu thức chính quy `/at(.)?$/gm` có nghĩa là: ký tự chữ thường `a`, theo sau là ký tự chữ thường `t`, tùy chọn mọi thứ trừ dòng mới. Và vì cờ `m` bây giờ công cụ biểu thức chính quy khớp với mẫu ở cuối mỗi dòng trong một chuỗi. + + +
+"/.at(.)?$/" => The fat + cat sat + on the mat. ++ +[Test the regular expression](https://regex101.com/r/hoGMkP/1) + +
+"/.at(.)?$/gm" => The fat + cat sat + on the mat. ++ +[Test the regular expression](https://regex101.com/r/E88WE2/1) + + + + +## 6. Greedy vs lazy matching + + +Theo mặc định, regex sẽ thực hiện greedy matching, có nghĩa là nó sẽ khớp càng lâu càng tốt. chúng ta có thể sử dụng `?` để khớp theo cách lười biếng có nghĩa là càng ngắn càng tốt + + + + +
+"/(.*at)/" => The fat cat sat on the mat.+ + +[Test the regular expression](https://regex101.com/r/AyAdgJ/1) + +
+"/(.*?at)/" => The fat cat sat on the mat.+ + +[Test the regular expression](https://regex101.com/r/AyAdgJ/2) + + +## Contribution + +* Open pull request with improvements +* Discuss ideas in issues +* Spread the word +* Reach out with any feedback [](https://twitter.com/ziishaned) + +## License + +MIT © [Zeeshan Ahmad](https://twitter.com/ziishaned) + + + + + + diff --git a/README-cn.md b/translations/README-zh-simple.md similarity index 90% rename from README-cn.md rename to translations/README-zh-simple.md index 84cc721f..83b4d8ab 100644 --- a/README-cn.md +++ b/translations/README-zh-simple.md @@ -1,15 +1,41 @@ -
-
-
-
+
@@ -438,11 +464,11 @@ ### 5.3 多行修饰符 (Multiline) -多行修饰符 `m` 常用语执行一个多行匹配. +多行修饰符 `m` 常用于执行一个多行匹配. 像之前介绍的 `(^,$)` 用于检查格式是否是在待检测字符串的开头或结尾. 但我们如果想要它在每行的开头和结尾生效, 我们需要用到多行修饰符 `m`. -例如, 表达式 `/at(.)?$/gm` 表示在待检测字符串每行的末尾搜索 `at`后跟一个或多个 `.` 的字符串, 并返回全部结果. +例如, 表达式 `/at(.)?$/gm` 表示在待检测字符串每行的末尾搜索 `at`后跟0个或1个 `.` 的字符串, 并返回全部结果."/.at(.)?$/" => The fat @@ -469,7 +495,7 @@ * *整数*: `^-?\d+$` * *用户名*: `^[\w\d_.]{4,16}$` * *数字和英文字母*: `^[a-zA-Z0-9]*$` -* *数字和英文字母和空格*: `^[a-zA-Z0-9 ]*$` +* *数字和应为字母和空格*: `^[a-zA-Z0-9 ]*$` * *密码*: `^(?=^.{6,}$)((?=.*[A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z]))^.*$` * *邮箱*: `^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})*$` * *IP4 地址*: `^((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))*$` @@ -490,4 +516,4 @@ ## 许可证 -MIT © [Zeeshan Ahmed](mailto:ziishaned@gmail.com) +MIT © [Zeeshan Ahmad](https://twitter.com/ziishaned) diff --git a/translations/how-to.md b/translations/how-to.md new file mode 100644 index 00000000..91b6081d --- /dev/null +++ b/translations/how-to.md @@ -0,0 +1,9 @@ +Please put new translation README files here. + +To start a new translation, please: + +1. Make an issue (for collaboration with other translators) +2. Make a pull request to collaborate and commit to. +3. Let me know when it's ready to pull. + +Thank you! \ No newline at end of file