Any word character regex

.* and .+ are for any chars except for new lines.

Double Escaping

Just in case, you would wanted to include new lines, the following expressions might also work for those languages that double escaping is required such as Java or C++:

[\s\S]*
[\d\D]*
[\w\W]*

for zero or more times, or

[\s\S]+
[\d\D]+
[\w\W]+

for one or more times.

Single Escaping:

Double escaping is not required for some languages such as, C#, PHP, Ruby, PERL, Python, JavaScript:

[sS]*
[dD]*
[wW]*
[sS]+
[dD]+
[wW]+

Test

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RegularExpression{

    public static void main(String[] args){

        final String regex_1 = "[\s\S]*";
        final String regex_2 = "[\d\D]*";
        final String regex_3 = "[\w\W]*";
        final String string = "AAA123nt"
             + "ABCDEFGH123nt"
             + "XXXX123nt";

        final Pattern pattern_1 = Pattern.compile(regex_1);
        final Pattern pattern_2 = Pattern.compile(regex_2);
        final Pattern pattern_3 = Pattern.compile(regex_3);

        final Matcher matcher_1 = pattern_1.matcher(string);
        final Matcher matcher_2 = pattern_2.matcher(string);
        final Matcher matcher_3 = pattern_3.matcher(string);

        if (matcher_1.find()) {
            System.out.println("Full Match for Expression 1: " + matcher_1.group(0));
        }

        if (matcher_2.find()) {
            System.out.println("Full Match for Expression 2: " + matcher_2.group(0));
        }
        if (matcher_3.find()) {
            System.out.println("Full Match for Expression 3: " + matcher_3.group(0));
        }
    }
}

Output

Full Match for Expression 1: AAA123
    ABCDEFGH123
    XXXX123

Full Match for Expression 2: AAA123
    ABCDEFGH123
    XXXX123

Full Match for Expression 3: AAA123
    ABCDEFGH123
    XXXX123

If you wish to explore the expression, it’s been explained on the top right panel of regex101.com. If you’d like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Cover image for Basic RegEx in Javascript for beginners 🔥

What is regular expression

This is a sequence of character that define a search pattern in a form or text. It is used in popular languages like Javascript, Go, Python, Java, C# which supports regex fully. Text editors like Atom, Sublime and VS code editor use it to find and replace matches in your code.
Example in vs code editor. Click (ALT+ R) to use regex

regex view in vs code

Applications

  • Grabbing HTML tags
  • Trimming white spaces
  • Removing duplicate text
  • Finding or verifying card numbers
  • Form Validation
  • Matching Ip addresses
  • Matching a specific word in a large block of text.

Literal character

It matches a single character. Example, if you want to match character ‘e’ in bees and cats.

Meta character

Match a range of characters. Example lets do an easy regex to find specific numbers 643 in a series of numbers.It will only match 643 not the rest of the numbers. I am using Regex101

simple regex

Two ways of writing regex

   1) const regex = /[a-z]/gi;
   2) const regex = new RegExp(/[a-z], 'gi'/);

Enter fullscreen mode

Exit fullscreen mode

Different types of meta characters include:

1) Single character

   let regex; 
  // shorthand for the single characters 
   regex = /d/; //Matches any digital character
   regex = /w/; // Matches any word character [a-zA-z0-9_]
   regex = /s/; // Matches any whitespace
   regex = /./;  //Matches any character except line terminators
   regex = /W/; //Matches any non-word characters. Anything that's not [^a-zA-z0-9]
   regex = /S/; // Matches any non whitespace
   regex = /D/; //Matches any non-digit character [^0-9]
   regex = /b/; //assert position at a word boundary
   regex = /B/; // matches non-boundary word

   // Single characters
   regex = /[a-z]/; // Matches lowercase letters between a-z (char code 97-122)
   regex = /[A-Z]/; // Matches uppercase letters between A-z (char code 65-90)
   regex = /[0-9]/; // Matches digits numbers between 0-9 (char code 48- 57)
   regex = /[a-zA-Z]/; // matches matches both lower and uppercase letters
   regex = /./ ; // matches literal character . (char code 46)
   regex = /(/ ; // matches literal character (
   regex = /)/ ; // matches literal character )
   regex = /-/ ; // matches literal character - (char code 95)

Enter fullscreen mode

Exit fullscreen mode

2) Quantifiers

They measure how many times you want the single characters to appear.

   * : 0 or more
   + : 1 or more
   ? : 0 or 1
   {n,m} : min and max
   {n} : max
  /^[a-z]{5,8}$/; //Matches 5-8 letters btw a-z
  /.+/;  // Matches at least one character to unlimited times
 const regex = /^d{3}-d{3}-d{4}$/; // Matches 907-643-6589

const regex = /^(?d{3})?$/g  // matches (897) or 897

const regex = /.net|.com|.org/g // matches .com or .net or .org

Enter fullscreen mode

Exit fullscreen mode

3) Position

  ^ : asserts position at the start
  $ : asserts position at the end
 b : word boundary
 const regex = /bw+{4}b/; // Matches four letter word.

Enter fullscreen mode

Exit fullscreen mode

If you want to look for words with any 4 word character use b without the boundary it will select any 4 word letters from word characters.
regex with boundary

Character Classes

This are characters that appear with the square brackets […]

   let regex;
   regex = /[-.]/; //match a literal . or - character
   regex = /[abc]/; //match character a or b or c
   regex =/^(?d{3})?[-.]d{3}[-.]d{4}$/; // matches (789)-876-4378, 899-876-4378 and 219.876.4378

Enter fullscreen mode

Exit fullscreen mode

Capturing groups

This is used to separate characters within a regular expression and is enclosed with parentheses (….)
The below regex pattern captures different groups of the numbers
regex pattern

Capturing groups is useful when you want to find and replace some characters. Example you can capture a phone number or a card number and replace it by showing only the first 3-4 digits. Take a look at the example below.
regex pattern

//How to create a regex pattern for email address

 const regex = /^(w+)@(w+).([a-z]{2,8})([.a-z]{2,8})?$/

// It matches janetracy@jsninja.co.uk or janetracy@hey.com

Enter fullscreen mode

Exit fullscreen mode

Back reference

You can capture a group within a regex pattern by using (1)

   const regex = /^b(w+)s1b$/;
   // This will capture repeated words in a text.

Enter fullscreen mode

Exit fullscreen mode

Back reference can be used to replace markdown text to html.
regex pattern

Types of methods used regular expression

1) Test method

This is a method that you can call on a string and using a regular expression as an argument and returns a boolean as the result. True if the match was found and false if no match found.

const regex = /^d{4}$/g; 
regex.test('4567'); // output is true

Enter fullscreen mode

Exit fullscreen mode

2) match method

It is called on a string with a regular expression and returns an array that contains the results of that search or null if no match is found.

const s = 'Hello everyone, how are you?';
const regex = /how/;
s.match(regex);
// output "how"

Enter fullscreen mode

Exit fullscreen mode

3) exec method

It executes a search for a match in a specified string. Returns a result array or null. Both full match and captured groups are returned.

   const s = '234-453-7825';
   const regex = /^(d{3})[-.](d{3})[.-](d{4})$/;
   regex.exec(s);
//output ["234-453-7825", "234", "453", "7825"]

Enter fullscreen mode

Exit fullscreen mode

4) replace method

Takes in two arguments, regex and the string/ callback function you want to replace it with. This method is really powerful and can be used to create different projects like games.

  const str = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';
  const regex = /bw{4,6}b/g;
 const results = str.replace(regex, replace)

 function replace(match){
  return 'replacement';
}
// output 
replacement replacement replacement sit replacement, consectetur adipiscing replacement, sed do eiusmod replacement incididunt ut replacement et replacement replacement replacement.

Enter fullscreen mode

Exit fullscreen mode

5) split method

The sequence of character that makes where you should split the text. You can call the method it on a string and it takes regular expression as an argument.

   const s = 'Regex is very useful, especially when verifying card 
   numbers, forms and phone numbers';
   const regex = /,s+/;
   regex.split(s);
  // output ["Regex is very useful", "especially when verifying card numbers", "forms and phone numbers"]
// Splits the text where is a , or whitespace

Enter fullscreen mode

Exit fullscreen mode

Let’s make a small fun project

We want to make a textarea, where you can write any word character and when you click the submit button, the text generated will be individual span tags. When you hover on the span text, background color will change and also the text to (Yesss!!).
Let’s do this!!!!!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Regex expression</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>Regex expression exercises</h1>
    <div class="text-container">
        <textarea name="textarea" id="textarea" class = "textarea" cols="60" rows="10">
            Coronavirus disease (COVID-19) is an infectious disease caused by a newly discovered coronavirus.

            Most people 234-9854 infected with the COVID-19 virus will experience mild to moderate respiratory illness and recover without requiring special treatment.  Older people, and those with underlying medical problems like cardiovascular disease, diabetes, chronic respiratory disease, and cancer are more likely to develop serious illness.

            The best way to prevent and slow down 456-2904 transmission is be well informed about the COVID-19 virus, the disease it causes and how it spreads. Protect yourself and others from infection by washing your hands or using an alcohol based rub frequently and not touching your face. 

            The COVID-19 virus spreads 860-8248 primarily through droplets of saliva or discharge from the nose when an infected person coughs or sneezes, so it’s important that you also practice respiratory etiquette (for example, by coughing into a flexed elbow).        </textarea>
        <div class="result-text">
        </div>
        <button type="submit">Submit</button>
      </div>

    <script src="regex.js"></script>
</body>
</html>

Enter fullscreen mode

Exit fullscreen mode

Let’s write the Javascript part

const button = document.querySelector('button');
const textarea = document.querySelector('textarea');
const resultText = document.querySelector('.result-text');

function regexPattern (){

    const regex = /(W+)/g;
    const str = textarea.value;


    const results = str.split(regex);
    console.log(results);


    results.forEach(result =>{
        if(result != null){
            const span = document.createElement('span');
            span.innerHTML = result;
            resultText.appendChild(span);




            span.addEventListener ('mouseover', () => {
                const randomColour = Math.floor(Math.random()* 255);
                const randomColour1 = Math.floor(Math.random()* 255);
                const randomColour2 = Math.floor(Math.random()* 255);
                span.style.backgroundColor = `rgba(${randomColour}, ${randomColour1}, ${randomColour2})`; 
                span.textContent = 'Yesss!'               
            });

        }        

    });


};

button.addEventListener('click', () => {
    resultText.innerHTML += `<p class ='text-info'>This is what I matched</P>`;

    regexPattern();
});

Enter fullscreen mode

Exit fullscreen mode

results

regex project
Source code in my GitHub
Watch the result video

Websites resources for learning regex in Js

  • 💻Regular expression info
  • 💻Regex.com
  • 💻Regexone
  • 💻Regex101

Youtube videos

  • 🎥Regular Expressions (Regex) Mini Bootcamp by Colt Steele
  • 🎥Learn Regular Expressions In 20 Minutes by Web Dev Simplified
  • 🎥Regular Expressions (RegEx) Tutorial by NetNinja
  • 🎥Regular Expressions (Regex) in JavaScript by FreecodeCamp

Books

  • 📖Mastering Regular Expressions by Jeffrey E. F. Friedl
  • 📕Regular Expressions Cookbook by Jan Goyvaerts
  • 📙Introducing Regular Expressions by Michael Fitzgerald

Conclusion

As a code newbie I was terrified when i first saw how regex looks like but this week, I decided to learn it and write about. To be honest I will use this post as a future reference, I hope you will too.
Now that you know how powerful regex is and where it can be applied. Especially in form validation or card number validation. I hope this helps any beginner to understand how powerful regex can be and how to use it.

In Regular Expressions a pattern match is denoted by /Pattern/ or m/pattern/

characters

Meta characters

  • * matches 0 or more of previous expression.
  • + matches 1 or more of previous expression.
  • ? matches 0 or 1 of previous expression; also forces minimal matching when an expression might match several strings within a search string.
  • . matches Any character (except n newline)
  • ( ) matches Logical grouping of part of an expression.
  • [ ] matches Explicit set of characters to match.
  • { } matches Explicit quantifier notation.
  • matches Preceding one of the above, it makes it a literal instead of a special character. Preceding a special matching character, see below.
  • / matches
  • | matches
  • ^ matches Beginning of a string.
  • $ matches End of a string.

literal characters

characters Classes

  • . matches any character except new line
  • [aeiou] matches any character in the specified set
  • [^aeiou] matches any character not in the specified set
  • [0-9a-eA-E] matches any character in the range of char before the hyphen and after the hyphen. In this example it would match any char between(and including) 0 thru 9 or lowercase a thru f or uppercase A thru F. Equivalent to [01234565789abcdeABCDE]
  • p{name} matches any character in the named character class specified by {name}. Supported names are Unicode groups and block ranges. For example, Ll, Nd, Z, IsGreek, IsBoxDrawing.
  • P{name} matches text not included in groups and block ranges specified in {name}.
  • w matches any word character. Equivalent to the Unicode character categories [p{Ll}p{Lu}p{Lt}p{Lo}p{Nd}p{Pc}].
  • W matches Matches any nonword character. Equivalent to the Unicode categories [^p{Ll}p{Lu}p{Lt}p{Lo}p{Nd}p{Pc}]
  • s matches any white-space character. Equivalent to the Unicode character categories [fnrtvx85p{Z}]
  • S matches any non-white-space character. Equivalent to the Unicode character categories [^fnrtvx85p{Z}]
  • d Matches any decimal digit. Equivalent to p{Nd} for Unicode and [0-9] for non-Unicode, ECMAScript behavior.
  • D matches any nondigit. Equivalent to P{Nd} for Unicode and [^0-9] for non-Unicode
  • b A word boundary, the spot between word (w) and non-word (W) characters /bfredb/i matches Fred but not Alfred or Frederick

POSIX Character Classes

  • [:alnum:] matches alphanumeric character [:alnum:]{3} matches any three letters or numbers, like 7Ds
  • [:alpha:] alphabetic character, any case [:alpha:]{5} matches five alphabetic characters, any case, like aBcDe
  • [:blank:] matches space and tab [:blank:]{3,5} matches any three, four, or five spaces and tabs
  • [:digit:] matches digits [:digit:]{3,5} matches any three, four, or five digits, like 3, 05, 489
  • [:lower:] matches lowercase alphabetics [:lower:] matches a but not A
  • [:punct:] matches punctuation characters [:punct:] matches ! or . or, but not an or 3
  • [:space:] matches all whitespace characters, including newline and carriage return [:space:] matches any space, tab, newline, or carriage return
  • [:upper:] matches uppercase alphabetics [:upper:] matches A but not

Meta characters

  • t matches tab (HT, TAB)
  • n matches newline (LF, NL)
  • r matches return (CR)
  • f matches form feed (FF)
  • a matches alarm (bell) (BEL)
  • e matches escape (think troff) (ESC)
  • 33 matches octal charcters (think of a PDP-11)
  • x1B matches hex characters]]
  • x{263a} matches wide hex characters (Unicode SMILEY)
  • c[ matches control characters
  • N{name} matches named characters
  • l matches lowercase next char (think vi)
  • u matches uppercase next char (think vi)
  • L matches lowercase till E (think vi)
  • U matches uppercase till E (think vi)
  • E matches end case modification (think vi)
  • Q matches quote (disable) pattern meta characters till E

Repetitions Oborators

  • * matches Match 0 or more times
  • + matches Match 1 or more times
  •  ? matches Match 1 or 0 times
  • {n} matches Match exactly n times
  • {n,} matches Match at least n times
  • {n,m} matches Match at least n but not more than m times

Anchoring Operators

  • ^ matches match must start the beginning of the line. example ^foo
  • $ matches match must start the beginning of the line.

Word Operators

  • b matches string at either the beginning or the end of a word. For example, `bratb’ matches the separate word `rat’.
  • B matches string within a word. For example, `cBratBe’ matches `crate’, but `dirty Brat’ doesn’t match `dirty rat’.
  • < matches string at the beginning of a word
  • > matches string at the end of a word.
  • w matches any word-constituent character
  • W matches any character that is not word-constituent.

Buffer Operators

Following are operators which work on buffers. In Emacs, a buffer is, naturally, an Emacs buffer. For other programs, Regex considers the entire string to be matched as the buffer.

  • ` matches a string at the beginning of the buffer
  • matches a string at the end of the buffer

Greedy Wildcards and Repetitions

  •  ? Match 0 or more times
  • +? Match 1 or more times
  •  ?? Match 0 or 1 time
  • {n}? Match exactly n times
  • {n,}? Match at least n times
  • {n,m}? Match at least n but not more than m times

Groups, List

  • ( ) group operator
    • example (cat|hat) matched cat or hat
  • [ ] class operator
    • example [jfet] matches j or f or e or t

From HowTo Wiki, a Wikia wiki.

Regular expressions are a concise and flexible tool for describing
patterns in strings. This vignette describes the key features of
stringr’s regular expressions, as implemented by stringi. It is not a
tutorial, so if you’re unfamiliar regular expressions, I’d recommend
starting at https://r4ds.had.co.nz/strings.html. If you want to
master the details, I’d recommend reading the classic Mastering
Regular Expressions
by Jeffrey E. F. Friedl.

Regular expressions are the default pattern engine in stringr. That
means when you use a pattern matching function with a bare string, it’s
equivalent to wrapping it in a call to regex():

You will need to use regex() explicitly if you want to
override the default options, as you’ll see in examples below.

Basic matches

The simplest patterns match exact strings:

x <- c("apple", "banana", "pear")
str_extract(x, "an")
#> [1] NA   "an" NA

You can perform a case-insensitive match using
ignore_case = TRUE:

bananas <- c("banana", "Banana", "BANANA")
str_detect(bananas, "banana")
#> [1]  TRUE FALSE FALSE
str_detect(bananas, regex("banana", ignore_case = TRUE))
#> [1] TRUE TRUE TRUE

The next step up in complexity is ., which matches any
character except a newline:

You can allow . to match everything, including
n, by setting dotall = TRUE:

Escaping

If “.” matches any character, how do you match a literal
.”? You need to use an “escape” to tell the regular
expression you want to match it exactly, not use its special behaviour.
Like strings, regexps use the backslash, , to escape
special behaviour. So to match an ., you need the regexp
.. Unfortunately this creates a problem. We use strings to
represent regular expressions, and is also used as an
escape symbol in strings. So to create the regular expression
. we need the string "\.".

# To create the regular expression, we need \
dot <- "\."

# But the expression itself only contains one:
writeLines(dot)
#> .

# And this tells R to look for an explicit .
str_extract(c("abc", "a.c", "bef"), "a\.c")
#> [1] NA    "a.c" NA

If is used as an escape character in regular
expressions, how do you match a literal ? Well you need to
escape it, creating the regular expression \. To create
that regular expression, you need to use a string, which also needs to
escape . That means to match a literal you
need to write "\\" — you need four backslashes to match
one!

In this vignette, I use . to denote the regular
expression, and "\." to denote the string that represents
the regular expression.

An alternative quoting mechanism is Q...E: all the
characters in ... are treated as exact matches. This is
useful if you want to exactly match user input as part of a regular
expression.

x <- c("a.b.c.d", "aeb")
starts_with <- "a.b"

str_detect(x, paste0("^", starts_with))
#> [1] TRUE TRUE
str_detect(x, paste0("^\Q", starts_with, "\E"))
#> [1]  TRUE FALSE

Special characters

Escapes also allow you to specify individual characters that are
otherwise hard to type. You can specify individual unicode characters in
five ways, either as a variable number of hex digits (four is most
common), or by name:

  • xhh: 2 hex digits.

  • x{hhhh}: 1-6 hex digits.

  • uhhhh: 4 hex digits.

  • Uhhhhhhhh: 8 hex digits.

  • N{name}, e.g. N{grinning face}
    matches the basic smiling emoji.

Similarly, you can specify many common control characters:

  • a: bell.

  • cX: match a control-X character.

  • e: escape (u001B).

  • f: form feed (u000C).

  • n: line feed (u000A).

  • r: carriage return (u000D).

  • t: horizontal tabulation
    (u0009).

  • ooo match an octal character. ‘ooo’ is from one to
    three octal digits, from 000 to 0377. The leading zero is
    required.

(Many of these are only of historical interest and are only included
here for the sake of completeness.)

Matching multiple characters

There are a number of patterns that match more than one character.
You’ve already seen ., which matches any character (except
a newline). A closely related operator is X, which matches
a grapheme cluster, a set of individual elements that
form a single symbol. For example, one way of representing “á” is as the
letter “a” plus an accent: . will match the component “a”,
while X will match the complete symbol:

There are five other escaped pairs that match narrower classes of
characters:

  • d: matches any digit. The complement,
    D, matches any character that is not a decimal digit.

    Technically, d includes any character in the Unicode
    Category of Nd (“Number, Decimal Digit”), which also includes numeric
    symbols from other languages:

    # Some Laotian numbers
    str_detect("១២៣", "\d")
    #> [1] TRUE
  • s: matches any whitespace. This includes tabs,
    newlines, form feeds, and any character in the Unicode Z Category (which
    includes a variety of space characters and other separators.). The
    complement, S, matches any non-whitespace character.

    (text <- "Some  t badlynttspaced f text")
    #> [1] "Some  t badlynttspaced f text"
    str_replace_all(text, "\s+", " ")
    #> [1] "Some badly spaced text"
  • p{property name} matches any character with
    specific unicode property, like p{Uppercase} or
    p{Diacritic}. The complement,
    P{property name}, matches all characters without the
    property. A complete list of unicode properties can be found at http://www.unicode.org/reports/tr44/#Property_Index.

    (text <- c('"Double quotes"', "«Guillemet»", "“Fancy quotes”"))
    #> [1] ""Double quotes"" "«Guillemet»"       "“Fancy quotes”"
    str_replace_all(text, "\p{quotation mark}", "'")
    #> [1] "'Double quotes'" "'Guillemet'"     "'Fancy quotes'"
  • w matches any “word” character, which includes
    alphabetic characters, marks and decimal numbers. The complement,
    W, matches any non-word character.

    str_extract_all("Don't eat that!", "\w+")[[1]]
    #> [1] "Don"  "t"    "eat"  "that"
    str_split("Don't eat that!", "\W")[[1]]
    #> [1] "Don"  "t"    "eat"  "that" ""

    Technically, w also matches connector punctuation,
    u200c (zero width connector), and u200d
    (zero width joiner), but these are rarely seen in the wild.

  • b matches word boundaries, the transition between
    word and non-word characters. B matches the opposite:
    boundaries that have either both word or non-word characters on either
    side.

    str_replace_all("The quick brown fox", "\b", "_")
    #> [1] "_The_ _quick_ _brown_ _fox_"
    str_replace_all("The quick brown fox", "\B", "_")
    #> [1] "T_h_e q_u_i_c_k b_r_o_w_n f_o_x"

You can also create your own character classes using
[]:

  • [abc]: matches a, b, or c.
  • [a-z]: matches every character between a and z (in
    Unicode code point order).
  • [^abc]: matches anything except a, b, or c.
  • [^-]: matches ^ or -.

There are a number of pre-built classes that you can use inside
[]:

  • [:punct:]: punctuation.
  • [:alpha:]: letters.
  • [:lower:]: lowercase letters.
  • [:upper:]: upperclass letters.
  • [:digit:]: digits.
  • [:xdigit:]: hex digits.
  • [:alnum:]: letters and numbers.
  • [:cntrl:]: control characters.
  • [:graph:]: letters, numbers, and punctuation.
  • [:print:]: letters, numbers, punctuation, and
    whitespace.
  • [:space:]: space characters (basically equivalent to
    s).
  • [:blank:]: space and tab.

These all go inside the [] for character classes,
i.e. [[:digit:]AX] matches all digits, A, and X.

You can also using Unicode properties, like
[p{Letter}], and various set operations, like
[p{Letter}--p{script=latin}]. See
?"stringi-search-charclass" for details.

Alternation

| is the alternation operator, which
will pick between one or more possible matches. For example,
abc|def will match abc or
def:

str_detect(c("abc", "def", "ghi"), "abc|def")
#> [1]  TRUE  TRUE FALSE

Note that the precedence for | is low:
abc|def is equivalent to (abc)|(def) not
ab(c|d)ef.

Grouping

You can use parentheses to override the default precedence rules:

str_extract(c("grey", "gray"), "gre|ay")
#> [1] "gre" "ay"
str_extract(c("grey", "gray"), "gr(e|a)y")
#> [1] "grey" "gray"

Parenthesis also define “groups” that you can refer to with
backreferences, like 1, 2
etc, and can be extracted with str_match(). For example,
the following regular expression finds all fruits that have a repeated
pair of letters:

pattern <- "(..)\1"
fruit %>% 
  str_subset(pattern)
#> [1] "banana"      "coconut"     "cucumber"    "jujube"      "papaya"     
#> [6] "salal berry"

fruit %>% 
  str_subset(pattern) %>% 
  str_match(pattern)
#>      [,1]   [,2]
#> [1,] "anan" "an"
#> [2,] "coco" "co"
#> [3,] "cucu" "cu"
#> [4,] "juju" "ju"
#> [5,] "papa" "pa"
#> [6,] "alal" "al"

You can use (?:...), the non-grouping parentheses, to
control precedence but not capture the match in a group. This is
slightly more efficient than capturing parentheses.

str_match(c("grey", "gray"), "gr(e|a)y")
#>      [,1]   [,2]
#> [1,] "grey" "e" 
#> [2,] "gray" "a"
str_match(c("grey", "gray"), "gr(?:e|a)y")
#>      [,1]  
#> [1,] "grey"
#> [2,] "gray"

This is most useful for more complex cases where you need to capture
matches and control precedence independently.

Anchors

By default, regular expressions will match any part of a string. It’s
often useful to anchor the regular expression so that
it matches from the start or end of the string:

  • ^ matches the start of string.
  • $ matches the end of the string.

To match a literal “$” or “^”, you need to escape them,
$, and ^.

For multiline strings, you can use
regex(multiline = TRUE). This changes the behaviour of
^ and $, and introduces three new
operators:

  • ^ now matches the start of each line.

  • $ now matches the end of each line.

  • A matches the start of the input.

  • z matches the end of the input.

  • Z matches the end of the input, but before the
    final line terminator, if it exists.

Repetition

You can control how many times a pattern matches with the repetition
operators:

  • ?: 0 or 1.
  • +: 1 or more.
  • *: 0 or more.
x <- "1888 is the longest year in Roman numerals: MDCCCLXXXVIII"
str_extract(x, "CC?")
#> [1] "CC"
str_extract(x, "CC+")
#> [1] "CCC"
str_extract(x, 'C[LX]+')
#> [1] "CLXXX"

Note that the precedence of these operators is high, so you can
write: colou?r to match either American or British
spellings. That means most uses will need parentheses, like
bana(na)+.

You can also specify the number of matches precisely:

  • {n}: exactly n
  • {n,}: n or more
  • {n,m}: between n and m

By default these matches are “greedy”: they will match the longest
string possible. You can make them “lazy”, matching the shortest string
possible by putting a ? after them:

  • ??: 0 or 1, prefer 0.
  • +?: 1 or more, match as few times as possible.
  • *?: 0 or more, match as few times as possible.
  • {n,}?: n or more, match as few times as possible.
  • {n,m}?: between n and m, , match as few times as
    possible, but at least n.

You can also make the matches possessive by putting a +
after them, which means that if later parts of the match fail, the
repetition will not be re-tried with a smaller number of characters.
This is an advanced feature used to improve performance in worst-case
scenarios (called “catastrophic backtracking”).

  • ?+: 0 or 1, possessive.
  • ++: 1 or more, possessive.
  • *+: 0 or more, possessive.
  • {n}+: exactly n, possessive.
  • {n,}+: n or more, possessive.
  • {n,m}+: between n and m, possessive.

A related concept is the atomic-match parenthesis,
(?>...). If a later match fails and the engine needs to
back-track, an atomic match is kept as is: it succeeds or fails as a
whole. Compare the following two regular expressions:

The atomic match fails because it matches A, and then the next
character is a C so it fails. The regular match succeeds because it
matches A, but then C doesn’t match, so it back-tracks and tries B
instead.

Look arounds

These assertions look ahead or behind the current match without
“consuming” any characters (i.e. changing the input position).

  • (?=...): positive look-ahead assertion. Matches if
    ... matches at the current input.

  • (?!...): negative look-ahead assertion. Matches if
    ... does not match at the current
    input.

  • (?<=...): positive look-behind assertion. Matches
    if ... matches text preceding the current position, with
    the last character of the match being the character just before the
    current position. Length must be bounded
    (i.e. no * or +).

  • (?<!...): negative look-behind assertion. Matches
    if ... does not match text preceding the
    current position. Length must be bounded
    (i.e. no * or +).

These are useful when you want to check that a pattern exists, but
you don’t want to include it in the result:

x <- c("1 piece", "2 pieces", "3")
str_extract(x, "\d+(?= pieces?)")
#> [1] "1" "2" NA

y <- c("100", "$400")
str_extract(y, "(?<=\$)\d+")
#> [1] NA    "400"

There are two ways to include comments in a regular expression. The
first is with (?#...):

str_detect("xyz", "x(?#this is a comment)")
#> [1] TRUE

The second is to use regex(comments = TRUE). This form
ignores spaces and newlines, and anything everything after
#. To match a literal space, you’ll need to escape it:
"\ ". This is a useful way of describing complex regular
expressions:

phone <- regex("
  \(?       # optional opening parens
  (\d{3})   # area code
  \)?       # optional closing parens
  (?:-|\ )? # optional dash or space
  (\d{3})   # another three numbers
  (?:-|\ )? # optional dash or space
  (\d{3})   # three more numbers
  ", comments = TRUE)

str_match(c("514-791-8141", "(514) 791 8141"), phone)
#>      [,1]            [,2]  [,3]  [,4] 
#> [1,] "514-791-814"   "514" "791" "814"
#> [2,] "(514) 791 814" "514" "791" "814"

Like this post? Please share to your friends:
  • Any situation word перевод
  • Any questions what does this word mean
  • Any pdf to word converter download
  • Any pdf to excel converter free
  • Any page any word