Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var bio = ‘tomasz’
- .match - bio.match(/Tomasz/)
- .exec() - /Tomasz/.exec(bio) // same as match
- .test() - /Tomasz/.test(bio) // returns boolean
- bio.replace(/asz/, ek')
- SPECIAL CHARS: $ ( ) * + . ? [ ^ | ], use ‘\’ before it
- ‘.’ oznacza jakikolwiek znak, np do /1.3/ pasuje ‘123’, ‘163’, ‘1$5’
- Quantifiers
- ‘?’ oznacza ze znak przed jest opcjonalny np do /front-?end/ pasuje zarowno frontend jak i front-end
- ‘+’ oznacza jeden lub wiele poprzedzajacych znakow, czyli do /hej+/ pasuje ‘hej’ jak i ‘hejjjjj’, ale nie ‘he’
- ‘*’ - podobny do ‘+’ - tylko oznacza kazdy znak
- /a{3,4}/ - klamerki w takim wypadku oznaczaja dopuszczalna ilosc powtorzen znaku - czyli szukamy ‘aaa’ lub ‘aaaa’
- /a{5,}/ will match five or more of the letter a
- Flags
- are used to modify the behaviour of a regular expression, and they are specified after the expression (eg /your expression/ig).
- flaga //i (insensitive - niewrazliwy) sprawia ze nie uwzgledniamy wielkosic liter
- flaga // sprawia ze uwzgledniamy wielkosic liter
- 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.
- Character classes
- 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.
- Negated character classes
- 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".
- /[^a-c]/.test('abc'); - jesli nie ma dokladnie tych liter to zwraca false
- Character types
- Character types can be used as shorthand for common character classes. There are six character types:
- \d matches decimal digits (0-9),
- \s matches whitespace characters, and
- \w matches word characters (letters—including international characters—numbers and the underscore).
- The other three character types can be found by capitalising the first three character types, which will negate their effect;
- \S while match any non-whitespace character, for example.
- Positions
- 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.
- Capturing groups
- You can use parentheses to create groups, which can group multiple tokens together or store a result for later reference:
- /"(.+)"/
- 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().
- 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.
- Non-capturing groups
- 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.
- 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.
- (?: ... ) - Non-capturing parentheses group the regex so that you can apply regex operators, but do not capture anything.
- Quantifiers
- It's almost as if we don't have a group.
- 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:
- /^(?:Tomasz and )?I ate$/
- Write an expression which matches "ha" repeated two or more times (eg, "haha" or "hahahahaha"), and pass it the answer() function.
- Hint: your expression shouldn't match "hahah". Use anchors to ensure that it doesn't.
- The RegExp object
- 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:
- // Same as /regexp?/ig
- new RegExp('regexp?', 'ig');
- 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.
- re = new RegExp('(?:' + username + '\=)([a-z]*)', 'g'); re.exec(userData)
- Advanced replacement
- 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:
- var text = '*italic text*';
- var replace = '<em>$1</em>';
- text.replace(/\*([^*]+)\*/, replace);
- Write some similar code, but to turn the value of the boldText variable into a <strong> element.
- boldText.replace(/\*+([^*]+)\*+/, "<strong>$1</strong>");
- What do 'lazy' and 'greedy' mean in the context of regular expressions?
- <em>Hello World</em>
- 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.
- 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.
- Assertions
- 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.
- 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)/.
- Use an assertion to extract "6+3" from the partialSums variable. Don't use any literal digits, use \d.
- The syntax is: X(?=Y), it means "look for X, but match only if followed by Y"
- "1+1,2+2,3+3=,8+10,10+10+20,6+3=9,5+3"
- partialSums.match(/(\d\+\d)(?=\=\d)/)
- Negative assertions
- 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.
- 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.
- Use a positive assertion followed by a negative assertion to extract "3+3" from the partialSums variable.
- Z Ksizaki wyrazenia regularne - receptury
- $()*+.?[\^{| - 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.
- Notacja z nawiasami kwadratowymi bywa nazywana klasą znaków
- 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.
- Myślnik (-) umieszczony pomiędzy dwoma znakami tworzy przedział
Advertisement
Add Comment
Please, Sign In to add comment