Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmValidating Programming File formats using Regular Expressions

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 characters such as ?, %, #, /, and ‘:‘ in the filename.
  • Every file should be saved with the right suffix used for separate programming languages.
  • Some of the correct responses of the programming file extension are:
    • .java
    • .py
    • .c 
    • .PHP 
    • .class 

Valid Programming file format: 

file_name.extension_of_programming_language

Examples:

Input: file_name.java
Output: True

Input: .PHP_file_name
Output: False
Explanation: The programming file extension is not valid.

Approach: The problem can be solved based on the following idea:

Create a regex pattern to validate the number as written below: 

regex= ^.*\.(java|py|c|PHP|cs|cake|cshtml|csx|cpp|cp|cc|cobol|cob|ccp|css|flux|fx| go|jsp|kt|ktm|kts|numpy|numpyw|numsc|pls|pck|pkb|pks|plbplsql|sql|perl|r|rd|rsx|sh|bash|st|cs |swift|vb|class)$

Where,

  • ^ : indicates the start of the file
  • .*(dot-star): will match everything except a newline (\n).
  • |(Alternation) :Acts like a boolean OR and Matches the expression before or after the |.
  • \. (Escape character): matches a dot(.) character.
  • *(Quantifier): matches 0 or more of the preceding token(x)Capturing group: Matches x and remembers the match. For example, /(Rahul)/ matches and remembers “Rahul” in “Rahul Chauhan”.
  • $  : End of the string

Follow the below steps to implement the idea:

  • Create regex expression for the programming file names.
  • If the input string is empty, Therefore return false.
  • Else, Use the Pattern class to compile the regex formed.
  • Use the matcher function to check whether the UPI id is valid or not.
  • If it is valid, return true. Otherwise, return false.

Below is the implementation of the above approach.

C++




// C++ program to validate the
// Programming language file format Regular
// Expression
 
#include <bits/stdc++.h>
#include <regex>
using namespace std;
 
// Function to validate the
// Programming language file format
string isValidProgrammingFileFormat(string str)
{
    // Regex to check valid
    // Programming language file format.
    const regex pattern(
        "^.*\.(java|py|c|PHP|cs|cake|cshtml|csx|cpp|cp|cc|"
        "cobol|cob|ccp|css|flux|fx| "
        "go|jsp|kt|ktm|kts|numpy|numpyw|numsc|pls|pck|pkb|"
        "pks|plbplsql|sql|perl|r|rd|rsx|sh|bash|st|cs "
        "|swift|vb|class)$");
 
    // If the string is empty return false
    if (str.empty()) {
        return "false";
    }
 
    // Return true if the str
    // matched the ReGex
    if (regex_match(str, pattern)) {
        return "true";
    }
    else {
        return "false";
    }
}
 
// Driver Code
int main()
{
    // Test Case 1:
    string str1 = "file_name.java";
    cout << isValidProgrammingFileFormat(str1) << endl;
 
    // Test Case 2:
    string str2 = "file_name01.py";
    cout << isValidProgrammingFileFormat(str2) << endl;
 
    // Test Case 3:
    string str3 = "Java123";
    cout << isValidProgrammingFileFormat(str3) << endl;
 
    // Test Case 4:
    string str4 = "file_name.class";
    cout << isValidProgrammingFileFormat(str4) << endl;
 
    // Test Case 5:
    string str5 = "file_name.css";
    cout << isValidProgrammingFileFormat(str5) << endl;
 
    // Test Case 6:
    string str6 = ".PHP_file_name";
    cout << isValidProgrammingFileFormat(str6) << endl;
 
    return 0;
}


Java




// Java program to validate the
// Programming language file format using
// Regular Expression
 
import java.io.*;
import java.util.regex.*;
 
class GFG {
 
    // Function to validate the
    // Programming language file format
    public static boolean
    isValidProgrammingFileFormat(String str)
    {
 
        // Regex to check valid Programming
        // language file format
        String regex
            = "^.*\\.(java|py|c|PHP|cs|cake|cshtml|csx|c|cpp|cp|cc|cobol|cob|ccp|css|flux|fx|go|jsp|kt|ktm|kts|numpy|numpyw|numsc|pls|pck|pkb|pks|plbplsql|sql|perl|r|rd|rsx|sh|bash|st|cs|swift|vb|class)$";
 
        // Compile the ReGex
        Pattern p = Pattern.compile(regex);
 
        // If the string is empty return false
        if (str == null) {
            return false;
        }
 
        // Pattern class contains matcher()
        // method to find matching between
        // given Programming language file
        // format using regular expression.
        Matcher m = p.matcher(str);
 
        // Return if the str
        // matched the ReGex
        return m.matches();
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // Test Case 1:
        String str1 = "file_name.java";
        System.out.println(
            isValidProgrammingFileFormat(str1));
 
        // Test Case 2:
        String str2 = "file_name01.py";
        System.out.println(
            isValidProgrammingFileFormat(str2));
 
        // Test Case 3:
        String str3 = "Java123";
        System.out.println(
            isValidProgrammingFileFormat(str3));
 
        // Test Case 4:
        String str4 = "file_name.class";
        System.out.println(
            isValidProgrammingFileFormat(str4));
 
        // Test Case 5:
        String str5 = "file_name.css";
        System.out.println(
            isValidProgrammingFileFormat(str5));
 
        // Test Case 6:
        String str6 = ".PHP_file_name";
        System.out.println(
            isValidProgrammingFileFormat(str6));
    }
}


Python3




# Python3 program to validate
# Programming language file format using
# Regular Expression
 
import re
 
 
# Function to validate
# Programming language file format
def isValidProgrammingFileFormat(str):
 
    # Regex to check valid Programming language
    # file format
    regex = "^.*\.(java|py|c|PHP|cs|cake|cshtml|csx|cpp|cp|cc|cobol|cob|ccp|css|flux|fx| go|jsp|kt|ktm|kts|numpy|numpyw|numsc|pls|pck|pkb|pks|plbplsql|sql|perl|r|rd|rsx|sh|bash|st|cs |swift|vb|class)$"
 
    # Compile the ReGex
    p = re.compile(regex)
 
    # If the string is empty
    # return false
    if (str == None):
        return "false"
 
    # Return if the string
    # matched the ReGex
    if(re.search(p, str)):
        return "true"
    else:
        return "false"
 
 
# Driver code
if __name__ == '__main__':
     
    # Test Case 1:
    str1 = "file_name.java"
    print(isValidProgrammingFileFormat(str1))
     
    # Test Case 2:
    str2 = "file_name01.py"
    print(isValidProgrammingFileFormat(str2))
     
    # Test Case 3:
    str3 = "Java123"
    print(isValidProgrammingFileFormat(str3))
     
    # Test Case 4:
    str4 = "file_name.class"
    print(isValidProgrammingFileFormat(str4))
     
    # Test Case 5:
    str5 = "file_name.css"
    print(isValidProgrammingFileFormat(str5))
     
    # Test Case 6:
    str6 = ".PHP_file_name"
    print(isValidProgrammingFileFormat(str6))


C#




// C# program to validate the
// Programming language file format using
// Regular Expression
using System;
using System.Text.RegularExpressions;
 
public class GFG
{
 
  // Function to validate the
  // Programming language file format
  public static bool isValidProgrammingFileFormat(String str)
  {
 
    // Regex to check valid
    // Programming language file format.
    var regex = new Regex("^.*\\.(java|py|c|PHP|cs|cake|cshtml|csx|c|cpp|cp|cc|cobol|cob|ccp|css|flux|fx|go|jsp|kt|ktm|kts|numpy|numpyw|numsc|pls|pck|pkb|pks|plbplsql|sql|perl|r|rd|rsx|sh|bash|st|cs|swift|vb|class)$");
 
    // If the string is empty return false
    if (str == null)
    {
      return false;
    }
 
    // Pattern class contains matcher()
    // method to find matching between
    // given Programming language file
    // format using regular expression.
    var m = regex.Match(str);
 
    // Return if the str
    // matched the ReGex
    return m.Success;
  }
 
  // Driver Code.
  public static void Main(String[] args)
  {
    // Test Case 1:
    var str1 = "file_name.java";
    Console.WriteLine(
      isValidProgrammingFileFormat(str1));
 
    // Test Case 2:
    var str2 = "file_name01.py";
    Console.WriteLine(
      isValidProgrammingFileFormat(str2));
 
    // Test Case 3:
    var str3 = "Java123";
    Console.WriteLine(
      isValidProgrammingFileFormat(str3));
 
    // Test Case 4:
    var str4 = "file_name.class";
    Console.WriteLine(
      isValidProgrammingFileFormat(str4));
 
    // Test Case 5:
    var str5 = "file_name.css";
    Console.WriteLine(
      isValidProgrammingFileFormat(str5));
 
    // Test Case 6:
    var str6 = ".PHP_file_name";
    Console.WriteLine(
      isValidProgrammingFileFormat(str6));
 
  }
}
 
// This code is contributed by Pushpesh Raj.


Javascript




// Javascript program to validate
// Programming language file format using Regular Expression
 
// Function to validate the
// Programming language file format
function isValidProgrammingFileFormat(str) {
    // Regex to check valid
    // Programming language file format
    let regex = new RegExp(/^.*\.(java|py|c|PHP|cs|cake|cshtml|csx|cpp|cp|cc|cobol|cob|ccp|css|flux|fx| go|jsp|kt|ktm|kts|numpy|numpyw|numsc|pls|pck|pkb|pks|plbplsql|sql|perl|r|rd|rsx|sh|bash|st|cs |swift|vb|class)$/);
 
    // if str
    // is empty return false
    if (str == null) {
        return "false";
    }
 
    // Return true if the str
    // matched the ReGex
    if (regex.test(str) == true) {
        return "true";
    }
    else {
        return "false";
    }
}
 
// Driver Code
// Test Case 1:
let str1 = "file_name.java";
console.log(isValidProgrammingFileFormat(str1));
 
// Test Case 2:
let str2 = "file_name01.py";
console.log(isValidProgrammingFileFormat(str2));
 
// Test Case 3:
let str3 = "Java123";
console.log(isValidProgrammingFileFormat(str3));
 
// Test Case 4:
let str4 = "file_name.class";
console.log(isValidProgrammingFileFormat(str4));
 
// Test Case 5:
let str5 = "file_name.css";
console.log(isValidProgrammingFileFormat(str5));
 
// Test Case 6:
let str6 = ".PHP_file_name";
console.log(isValidProgrammingFileFormat(str6));


Output

true
true
false
true
true
false

Time Complexity: O(N) for each test case, where N is the length of the given string. 
Auxiliary Space: O(1)  

Related Articles:

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Ted Musemwa
As a software developer I’m interested in the intersection of computational thinking and design thinking when solving human problems. As a professional I am guided by the principles of experiential learning; experience, reflect, conceptualise and experiment.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments