mituri

Regexp

Mar 30th, 2020
509
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.11 KB | None | 0 0
  1. var bio = ‘tomasz’
  2.  
  3. .match - bio.match(/Tomasz/)
  4.  
  5. .exec() - /Tomasz/.exec(bio) // same as match
  6.  
  7. .test() - /Tomasz/.test(bio) // returns boolean
  8.  
  9.  
  10. bio.replace(/asz/, ek')
  11.  
  12.  
  13. SPECIAL CHARS: $ ( ) * + . ? [ ^ | ], use ‘\’ before it
  14.  
  15.  
  16. ‘.’ oznacza jakikolwiek znak, np do /1.3/ pasuje ‘123’, ‘163’, ‘1$5’
  17.  
  18.  
  19. Quantifiers
  20. ‘?’ oznacza ze znak przed jest opcjonalny np do /front-?end/ pasuje zarowno frontend jak i front-end
  21.  
  22. ‘+’ oznacza jeden lub wiele poprzedzajacych znakow, czyli do /hej+/ pasuje ‘hej’ jak i ‘hejjjjj’, ale nie ‘he’
  23.  
  24.  
  25. ‘*’ - podobny do ‘+’ - tylko oznacza kazdy znak
  26.  
  27. /a{3,4}/ - klamerki w takim wypadku oznaczaja dopuszczalna ilosc powtorzen znaku - czyli szukamy ‘aaa’ lub ‘aaaa’
  28.  
  29. /a{5,}/ will match five or more of the letter a
  30.  
  31.  
  32.  
  33. Flags
  34. are used to modify the behaviour of a regular expression, and they are specified after the expression (eg /your expression/ig).
  35.  
  36. flaga //i (insensitive - niewrazliwy) sprawia ze nie uwzgledniamy wielkosic liter
  37. flaga // sprawia ze uwzgledniamy wielkosic liter
  38.  
  39. glaga //g jak global - While /a/ only matches the first a in the string given to it, /a/g would match every single letter a.
  40.  
  41. Character classes
  42. Character classes allow you to specify a set or range of characters to be matched. /[aeiou]/ matches any vowel (samogloska), /[a-m]/ matches any letter in the first half of the alphabet, and /[aeiou0-9]/ matches any vowel or digit.
  43.  
  44.  
  45. Negated character classes
  46. A negated character class will match any character that isn't in the character class. You negate a character class by putting a caret character (^) at the beginning of the class. For example, /[^a-m]/ will match "z" and "$", but it will not match "c".
  47. /[^a-c]/.test('abc'); - jesli nie ma dokladnie tych liter to zwraca false
  48.  
  49.  
  50.  
  51. Character types
  52. Character types can be used as shorthand for common character classes. There are six character types:
  53. \d matches decimal digits (0-9),
  54. \s matches whitespace characters, and
  55. \w matches word characters (letters—including international characters—numbers and the underscore).
  56. The other three character types can be found by capitalising the first three character types, which will negate their effect;
  57. \S while match any non-whitespace character, for example.
  58.  
  59. Positions
  60. If you want to make sure that an expression starts or ends at a certain place in a word—for example, if you want to make sure that a string starts with a capital letter—then you can use an anchor. The dollar sign matches the end of a string, and the caret sign (^) matches the beginning. /^cat$/ will match "cat" and nothing else (while just /cat/ will match anything with "cat" in.
  61.  
  62.  
  63. Capturing groups
  64. You can use parentheses to create groups, which can group multiple tokens together or store a result for later reference:
  65. /"(.+)"/
  66. That's an example of a capturing group, meaning that the part of the matched string within the parentheses is saved to a later point in the array returned by .match() or .exec().
  67. Take our previous example where we grabbed the data between two parentheses using an expression like /\(.{5,8}\)/.exec(shorterStory). Try running that again, and then wrapping ".{5,8}" in parentheses and trying again.
  68.  
  69.  
  70. Non-capturing groups
  71. You can see that the array is now two items long: the first item is the entire match, and the second is only the data that the capturing group matched.
  72. There is another type of group called a non-capturing group. This type of group, which has a slightly different syntax, doesn't store the value to an array. If you don't need to refer back to the group, you should prefer a non-capturing group: it keeps the return array cleaner. Turn the group in the previous expression into a non-capturing group by inserting "?:" into the beginning of the group before the dot.
  73.  
  74. (?: ... ) - Non-capturing parentheses group the regex so that you can apply regex operators, but do not capture anything.
  75.  
  76.  
  77. Quantifiers
  78. It's almost as if we don't have a group.
  79. The main use of non-capturing groups is to apply a quantifier to a number of tokens. The following would match "I ate" and "Tomasz and I ate", but nothing else:
  80. /^(?:Tomasz and )?I ate$/
  81. Write an expression which matches "ha" repeated two or more times (eg, "haha" or "hahahahaha"), and pass it the answer() function.
  82.  
  83.  
  84. Hint: your expression shouldn't match "hahah". Use anchors to ensure that it doesn't.
  85. The RegExp object
  86. In addition to the literal operator (the slashes), JavaScript provides a RegExp constructor which allows you to specify your desired expression as a string. This is useful for putting variable in expressions. It works like this:
  87. // Same as /regexp?/ig
  88. new RegExp('regexp?', 'ig');
  89. The username contains a variable (still). The userData variable contains user data: print it to the console to see the format of the data. Use the username variable to extract the word associated with our user. Please put your entire answer on one line so that it can be validated.
  90.  
  91. re = new RegExp('(?:' + username + '\=)([a-z]*)', 'g'); re.exec(userData)
  92.  
  93.  
  94.  
  95. Advanced replacement
  96. We've seen two ways in which capturing groups can have their captured value used later on: the first was the returned array, and the second was in a backreference. You can also access them from the second argument of the string .replace() method:
  97. var text = '*italic text*';
  98. var replace = '<em>$1</em>';
  99. text.replace(/\*([^*]+)\*/, replace);
  100. Write some similar code, but to turn the value of the boldText variable into a <strong> element.
  101.  
  102. boldText.replace(/\*+([^*]+)\*+/, "<strong>$1</strong>");
  103.  
  104.  
  105. What do 'lazy' and 'greedy' mean in the context of regular expressions?
  106.  
  107. <em>Hello World</em>
  108. You may think that <.+> (. means any non newline character and + means one or more) would only match the <em> and the </em>, when in reality it will be very greedy, and go from the first < to the last >. This means it will match <em>Hello World</em> instead of what you wanted.
  109. Making it lazy (<.+?>) will prevent this. By adding the ? after the +, we tell it to repeat as few times as possible, so the first > it comes across, is where we want to stop the matching.
  110.  
  111.  
  112. Assertions
  113. An assertion is a pattern that should be matched, but will not be stored: so instead of "match a and then b", we have "match a that is followed by b, but don't match b". There are two types of assertion supported in JavaScript, positive lookaheads and negative lookaheads. Lookaheads just means looking forwards; JavaScript doesn't support lookbehinds.
  114. A positive lookahead means that we want to look ahead for a match. To look for an a followed by a b, we could use /a(?=b)/.
  115. Use an assertion to extract "6+3" from the partialSums variable. Don't use any literal digits, use \d.
  116.  
  117. The syntax is: X(?=Y), it means "look for X, but match only if followed by Y"
  118.  
  119. "1+1,2+2,3+3=,8+10,10+10+20,6+3=9,5+3"
  120. partialSums.match(/(\d\+\d)(?=\=\d)/)
  121.  
  122.  
  123. Negative assertions
  124. Assertions can also be negative, to say that you want to match something that isn't followed by something. Note that unlike a character class, this can match something that isn't that—if you say "a that isn't followed by b", the a can be at the end of the string.
  125. The syntax for a negative assertion is similar to that of a positive assertion, but you replace the equals sign with an exclamation mark: for example, /a(?!b)/ would find a letter a that isn't followed by a letter b.
  126. Use a positive assertion followed by a negative assertion to extract "3+3" from the partialSums variable.
  127.  
  128.  
  129.  
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136.  
  137.  
  138. Z Ksizaki wyrazenia regularne - receptury
  139.  
  140.  
  141. $()*+.?[\^{| - metaznaki - . Jeśli chcemy, aby nasze wyrażenie było literalnie dopasowane do tych znaków, powinniśmy użyć tzw. sekwencji ucieczki (ang. escape), czyli poprzedzić każdy z tych znaków lewym ukośnikiem.
  142.  
  143. Notacja z nawiasami kwadratowymi bywa nazywana klasą znaków
  144.  
  145. Znak karety, tzw. daszek (^), umieszczony bezpośrednio za otwierającym nawiasem kwadratowym neguje znaczenie danej klasy znaków. Oznacza to, że użycie tego znaku powoduje dopasowanie do dowolnego znaku, którego nie ma na liście.
  146.  
  147. Myślnik (-) umieszczony pomiędzy dwoma znakami tworzy przedział
Advertisement
Add Comment
Please, Sign In to add comment