Regular expressions in C - GeeksforGeeks (2024)

    • C
    • C Basics
    • C Data Types
    • C Operators
    • C Input and Output
    • C Control Flow
    • C Functions
    • C Arrays
    • C Strings
    • C Pointers
    • C Preprocessors
    • C File Handling
    • C Programs
    • C Cheatsheet
    • C Interview Questions
    • C MCQ
    • C++

    Open In App

    Last Updated : 01 Nov, 2023

    Summarize

    Comments

    Improve

    Suggest changes

    Like Article

    Like

    Save

    Report

    Prerequisite: How to write Regular Expressions?
    A regular expression is a sequence of characters that is used to search pattern. It is mainly used for pattern matching with strings, or string matching, etc. They are a generalized way to match patterns with sequences of characters. It is used in every programming language like C++, Java, and Python.
    Patterns in the POSIX Library

    ExpressionDescription
    []Used to find any of the characters or numbers specified between the brackets.
    [:number:]Used to find any digit.
    [:lower:]Used to find lowercase alphabets.
    [:word:]Used to find letters numbers and underscores.

    Creation of Regular Expression
    For compiling or creating the regular expression regcomp() function is used. It takes three arguments:
    Syntax:

    regcomp(&regex, expression, flag)

    where,

    1. regex is a pointer to a memory location where expression is matched and stored.
    2. expression is a string type
    3. flag to specify the type of compilation

    Return Value: This returns the value as shown below:

    • 0: when successful compilation is done.
    • Error_code: When there is unsuccessful compilation of the expression.

    Below is the illustration of the regcomp() function:

    C

    // C program for illustration of regcomp()

    #include <regex.h>

    #include <stdio.h>

    // Driver Code

    int main()

    {

    // Variable to create regex

    regex_t reegex;

    // Variable to store the return

    // value after creation of regex

    int value;

    // Function call to create regex

    value = regcomp( &reegex, "[:word:]", 0);

    // If compilation is successful

    if (value == 0) {

    printf("RegEx compiled successfully.");

    }

    // Else for Compilation error

    else {

    printf("Compilation error.");

    }

    return 0;

    }

    Output

    RegEx compiled successfully.

    Time complexity : O(n)
    Auxiliary Space : O(1)

    where n is the length of the pattern

    Matching of Pattern using Regular Expression
    The regexec() function is used to match a string against a pattern. It takes in five arguments:

    1. A precompiled pattern
    2. A string in which the pattern needs to be searched for.
    3. Information regarding the location of matches.
    4. Flags to specify a change in the matching behavior.

    Syntax:

    regexec(&regex, expression, 0, NULL, 0);

    where, regex = precompiled pattern,
    expression = pattern to be match in regex,
    NULL = Information regarding location of the matches.
    flag = to specify the change in matching behaviour
    Return Value: This returns the value as shown below:

    • 0: If there is a match.
    • REG_NOMATCH: If there is no match.

    Below is the illustration of the regexec() function:

    C

    // C program to illustrate the regexec() function

    #include <regex.h>

    #include <stdio.h>

    // Function to print the result

    void print_result(int value)

    {

    // If pattern found

    if (value == 0) {

    printf("Pattern found.\n");

    }

    // If pattern not found

    else if (value == REG_NOMATCH) {

    printf("Pattern not found.\n");

    }

    // If error occurred during Pattern

    // matching

    else {

    printf("An error occurred.\n");

    }

    }

    // Driver Code

    int main()

    {

    // Variable to store initial regex()

    regex_t reegex;

    // Variable for return type

    int value;

    int value2;

    // Creation of regEx

    value = regcomp( &reegex, "Welcome to GfG", 0);

    // Comparing pattern "GeeksforGeeks" with

    // string in reg

    value = regexec( &reegex, "GeeksforGeeks",

    0, NULL, 0);

    // Creation of regEx

    value2 = regcomp( &reegex, "GeeksforGeeks", 0);

    // Comparing pattern "Geeks"

    // with string in reg

    value2 = regexec( &reegex, "GeeksforGeeks",

    0, NULL, 0);

    // Print the results

    print_result(value);

    print_result(value2);

    return 0;

    }

    Output

    Pattern not found.Pattern found.

    Time complexity : O(n)
    Auxiliary Space : O(1)

    where n is the length of the pattern



    M

    Mindblender_3094

    Regular expressions in C - GeeksforGeeks (2)

    Improve

    Next Article

    Pointer Expressions in C with Examples

    Please Login to comment...

    Similar Reads

    Regular Expressions to Validate Google Analytics Tracking Id Given some Google Analytics Tracking IDs, the task is to check if they are valid or not using regular expressions. Rules for the valid Tracking Id are: It is an alphanumeric string i.e., containing digits (0-9), alphabets (A-Z), and a Special character hyphen(-).The hyphen will come in between the given Google Analytics Tracking Id.Google Analytics 5 min read Regular Expressions to Validate Provident Fund(PF) Account Number Given some PF(Provident Fund) Account Number, the task is to check if they are valid or not using regular expressions. Rules for the valid PF Account Number are : PF account number is alphanumeric String and forward slaces.First five characters are reserved for alphabet letters.Next 17 characters are reserved for digits(0-9).It allows only special 5 min read Count occurrences of a word in string | Set 2 (Using Regular Expressions) Given a string str and a word w, the task is to print the number of the occurrence of the given word in the string str using Regular Expression. Examples: Input: str = "peter parker picked a peck of pickled peppers”, w = "peck"Output: 1Explanation: There is only one occurrence of the word "peck" in the given string. Therefore, the output is 1. Inpu 4 min read Design finite automata from regular expressions Prerequisite - Finite automata, Regular expressions, grammar, and language. In this article, we will see some popular regular expressions and how we can convert them to finite automata (NFA and DFA). Let's discuss it one by one. Overview :Let a and b are input symbols and r is the regular expression. Now we have to design NFA as well as DFA for eac 3 min read US currency validation using Regular Expressions Given some US Currencies, the task is to check if they are valid or not using regular expressions. Rules for the valid Currency are: It should always start with "$".It can contain only digits (0 - 9) and at most one dot.It should not contain any whitespaces and alphabets.Comma Separator (', ') should be there after every three digits interval. Exam 5 min read Extracting PAN Number from GST Number Using Regular Expressions Given a string str in the form of a GST Number, the task is to extract the PAN Number from the given string. General Format of a GST Number: "22AAAAA0000A1Z5" 22: State CodeAAAAA0000A: Permanent Account Number (PAN)1: Entity Number of the same PANZ: Alphabet Z by default5: Checksum digit Examples: Input: str="23BOSPC9911R2Z5Output: BOSPC9911R Input 4 min read How to validate ISIN using Regular Expressions ISIN stands for International Securities Identification Number. Given string str, the task is to check whether the given string is a valid ISIN(International Securities Identification Number) or not by using Regular Expression. The valid ISIN(International Securities Identification Number) must satisfy the following conditions: It Should be the com 6 min read Validating UPI IDs using Regular Expressions Given some UPI IDs, the task is to check if they are valid or not using regular expressions. Rules for the valid UPI ID: UPI ID is an alphanumeric String i.e., formed using digits(0-9), alphabets (A-Z and a-z), and other special characters.It must contain '@'.It should not contain whitespace.It may or may not contain a dot (.) or hyphen (-). UPI st 6 min read Validate Gender using Regular Expressions Given some words of Gender, the task is to check if they are valid or not using regular expressions. The correct responses can be as given below: Male / male / MALE / M / mFemale / female / FEMALE / F / fNot prefer to say Example: Input: MOutput: True Input: SOutput: False Approach: The problem can be solved based on the following idea: Create a re 6 min read Validating Programming File formats using Regular Expressions Given some programming file names, the task is to check if they are valid or not using regular expressions. A valid programming file name follows the below conditions: It can contain alphabets (UpperCase or LowerCase), and digits and may contain a hyphen.It should contain one dot only that will be used as a suffix to save the file.Avoid special cha 6 min read Regular Expressions to Validate ISBN Code Given some ISBN Codes, the task is to check if they are valid or not using regular expressions. Rules for the valid codes are: It is a unique 10 or 13-digit.It may or may not contain a hyphen.It should not contain whitespaces and other special characters.It does not allow alphabet letters. Examples: Input: str = ”978-1-45678-123-4?Output: True Inpu 5 min read Regular Expressions to validate International Tracking of Imports Given some International Tracking of Imports, the task is to check if they are valid or not using regular expressions. Rules for the valid International Tracking of Imports are: It is an alphanumeric string i.e., It contains UpperCase alphabet letters (A-Z) and digits(0-9).It does not contain whitespaces and other special characters.Its length shou 5 min read Extracting all present dates in any given String using Regular Expressions Given a string Str, the task is to extract all the present dates from the string. Dates can be in the format i.e., mentioned below: DD-MM-YYYYYYYY-MM-DDDD Month YYYY Examples: Input: Str = "The First Version was released on 12-07-2008.The next Release will come on 12 July 2009. The due date for payment is 2023-09-1. India gained its freedom on 15 A 6 min read Regular Expressions to validate Loan Account Number (LAN) Given some Loan Account Number(LAN), the task is to check if they are valid or not using regular expressions. Rules for the valid Loan Account Number are: LAN is an alphanumeric string i.e., contains only digits (0-9) and uppercase alphabet characters.It does not allow whitespaces in it.It does not contain special characters.It starts with Uppercas 5 min read Regular Expressions to Validate Account Office Reference Number Given some Account Office Reference Number, the task is to check if they are valid or not using regular expressions. Rules for the valid Account Office Reference Number are: It is an alphanumeric string containing upper-case letters and digits.Accounts Office Reference Number is a unique, 13-character code.It starts with digits (0-9) and ends with 5 min read Extracting all Email Ids in any given String using Regular Expressions Given a string str, the task is to extract all the Email ID's from the given string. Example: Input: "Please send your resumes to Hr@[email protected] for any business inquiry please mail us at business@[email protected]"Output: Hr@[email protected]@[email protected] Approach: The problem can be solved based on the follo 4 min read Describe the procedure of extracting a query string with regular expressions A query string is a part of a URL that follows a question mark (?) and is used to pass data to a web page or application. It is typically composed of key-value pairs that are separated by an ampersand (&). The key represents the parameter and the value represents the data that is being passed through the parameter. In this article, we will disc 6 min read Extracting Repository Name from a Given GIT URL using Regular Expressions Given a string str, the task is to extract Repository Name from the given GIT URL. Examples: GIT URL can be any of the formats mentioned below: Input: str="git://github.com/book-Store/My-BookStore.git"Output: My-BookStoreExplanation: The Repo Name of the given URL is: My-BookStore Input: str="[email protected]:book-Store/My-BookStore.git"Output: My-Bo 4 min read Extracting Port Number from a localhost API Request to a Server using Regular Expressions Given a String test_str as localhost API Request Address, the task is to get the extract port number of the service. Examples: Input: test_str = ‘http://localhost:8109/users/addUsers’Output: 8109Explanation: Port Number, 8109 extracted. Input: test_str = ‘http://localhost:1337/api/products’Output: 1337Explanation: Port Number, 1337 extracted. Appro 5 min read Validating Indian currency data using Regular expressions Given some Indian Currency Data, the task is to check if they are valid or not using regular expressions. Rules for valid Indian Currency Data are: Indian Rupee format: The currency string starts with the Indian Rupee symbol ₹, followed by a comma-separated integer part that can have one to three digits, followed by a decimal point, followed by exa 5 min read Pointer Expressions in C with Examples Prerequisite: Pointers in C Pointers are used to point to address the location of a variable. A pointer is declared by preceding the name of the pointer by an asterisk(*). Syntax: datatype *pointer_name;When we need to initialize a pointer with variable's location, we use ampersand sign(&) before the variable name. Example: [GFGTABS] C // Decl 7 min read How to validate MAC address using Regular Expression Given string str, the task is to check whether the given string is a valid MAC address or not by using Regular Expression. A valid MAC address must satisfy the following conditions: It must contain 12 hexadecimal digits.One way to represent them is to form six pairs of the characters separated with a hyphen (-) or colon(:). For example, 01-23-45-67 6 min read How to clone a given regular expression in JavaScript ? In this article, we will know How to clone a regular expression using JavaScript. We can clone a given regular expression using the constructor RegExp(). The syntax of using this constructor has been defined as follows:- Syntax: new RegExp(regExp , flags) Here regExp is the expression to be cloned and flags determine the flags of the clone. There a 2 min read How to validate Indian driving license number using Regular Expression Given string str, the task is to check whether the given string is a valid Indian driving license number or not by using Regular Expression.The valid Indian driving license number must satisfy the following conditions: It should be 16 characters long (including space or hyphen (-)).The driving license number can be entered in any of the following f 7 min read How to validate CVV number using Regular Expression Given string str, the task is to check whether it is a valid CVV (Card Verification Value) number or not by using Regular Expression. The valid CVV (Card Verification Value) number must satisfy the following conditions: It should have 3 or 4 digits.It should have a digit between 0-9.It should not have any alphabet or special characters. Examples: I 5 min read Validate Corporate Identification Number (CIN) using Regular Expression Given some Corporate Identification Number, the task is to check if they are valid or not using regular expressions. Rules for the valid CIN are: CIN is a 21 digits alpha-numeric code.It starts with either alphabet letter U or L.Next five characters are reserved for digits (0-9).Next two places are occupied by alphabet letters(A-Z-a-z).Next four pl 6 min read How to validate GST (Goods and Services Tax) number using Regular Expression Given string str, the task is to check whether the given string is a valid GST (Goods and Services Tax) number or not using Regular Expression. The valid GST (Goods and Services Tax) number must satisfy the following conditions: It should be 15 characters long.The first 2 characters should be a number.The next 10 characters should be the PAN number 6 min read How to validate HTML tag using Regular Expression Given string str, the task is to check whether it is a valid HTML tag or not by using Regular Expression.The valid HTML tag must satisfy the following conditions: It should start with an opening tag (<).It should be followed by a double quotes string or single quotes string.It should not allow one double quotes string, one single quotes string o 6 min read How to validate IFSC Code using Regular Expression Given string str, the task is to check whether the given string is a valid IFSC (Indian Financial System) Code or not by using Regular Expression. The valid IFSC (Indian Financial System) Code must satisfy the following conditions: It should be 11 characters long.The first four characters should be upper case alphabets.The fifth character should be 8 min read How to validate MasterCard number using Regular Expression Given string str, the task is to check whether the given string is a valid Master Card number or not by using Regular Expression. The valid Master Card number must satisfy the following conditions. It should be 16 digits long.It should start with either two digits numbers may range from 51 to 55 or four digits numbers may range from 2221 to 2720.In 7 min read

    Article Tags :

    • Articles
    • C Programs
    • regular-expression

    Trending in News

    View More
    • How to Merge Cells in Google Sheets: Step by Step Guide
    • How to Lock Cells in Google Sheets : Step by Step Guide
    • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

    We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

    Regular expressions in C - GeeksforGeeks (3)

    Regular expressions in C - GeeksforGeeks (2024)
    Top Articles
    How Much Money Do You Need to Start Trading Futures? - TRADEPRO Academy TM
    Can Two Passwords Have The Same Hash? (Why?) – InfosecScout
    Nullreferenceexception 7 Days To Die
    Tryst Utah
    What spices do Germans cook with?
    Research Tome Neltharus
    Junk Cars For Sale Craigslist
    My Boyfriend Has No Money And I Pay For Everything
    How Much Is 10000 Nickels
    27 Places With The Absolute Best Pizza In NYC
    Osrs Blessed Axe
    Nj Scratch Off Remaining Prizes
    The fabulous trio of the Miller sisters
    Transfer Credits Uncc
    Craigslist Apartments In Philly
    Nj State Police Private Detective Unit
    D10 Wrestling Facebook
    Highland Park, Los Angeles, Neighborhood Guide
    Theresa Alone Gofundme
    Walgreens San Pedro And Hildebrand
    NBA 2k23 MyTEAM guide: Every Trophy Case Agenda for all 30 teams
    Babbychula
    Move Relearner Infinite Fusion
    January 8 Jesus Calling
    Is Holly Warlick Married To Susan Patton
    11526 Lake Ave Cleveland Oh 44102
    Jersey Shore Subreddit
    Kaliii - Area Codes Lyrics
    Little Einsteins Transcript
    Unm Hsc Zoom
    Nicole Wallace Mother Of Pearl Necklace
    CARLY Thank You Notes
    Pepsi Collaboration
    WorldAccount | Data Protection
    Craigslist Mexicali Cars And Trucks - By Owner
    Second Chance Apartments, 2nd Chance Apartments Locators for Bad Credit
    Academy Sports New Bern Nc Coupons
    Weather Underground Corvallis
    Umiami Sorority Rankings
    Simnet Jwu
    Clausen's Car Wash
    John Wick: Kapitel 4 (2023)
    Mcoc Black Panther
    Theater X Orange Heights Florida
    Mail2World Sign Up
    Shannon Sharpe Pointing Gif
    Is TinyZone TV Safe?
    786 Area Code -Get a Local Phone Number For Miami, Florida
    OSF OnCall Urgent Care treats minor illnesses and injuries
    Dr Seuss Star Bellied Sneetches Pdf
    Latest Posts
    Article information

    Author: Virgilio Hermann JD

    Last Updated:

    Views: 5261

    Rating: 4 / 5 (61 voted)

    Reviews: 92% of readers found this page helpful

    Author information

    Name: Virgilio Hermann JD

    Birthday: 1997-12-21

    Address: 6946 Schoen Cove, Sipesshire, MO 55944

    Phone: +3763365785260

    Job: Accounting Engineer

    Hobby: Web surfing, Rafting, Dowsing, Stand-up comedy, Ghost hunting, Swimming, Amateur radio

    Introduction: My name is Virgilio Hermann JD, I am a fine, gifted, beautiful, encouraging, kind, talented, zealous person who loves writing and wants to share my knowledge and understanding with you.