Showing posts with label Regular Expressions. Show all posts
Showing posts with label Regular Expressions. Show all posts

Saturday, 28 November 2020

MongoDB Regular Expression (Regex) - Pattern matching without the regex operator with Example- Part3

🚀 Master MongoDB Pattern Matching with Ram N Java!

Ready to search your data like a pro? Subscribe now for high-quality, beginner-friendly tech tutorials that make complex database queries and Regex operations simple to master!

🔔 SUBSCRIBE FOR FREE NOW

Pattern Matching in MongoDB: Regex Without the Operator

When searching for specific text patterns in your database, Regular Expressions (Regex) are incredibly powerful. While MongoDB has a dedicated $regex operator, did you know you can perform pattern matching directly using Regex literals? This approach is often cleaner and more concise for simple queries.

Using Regex Literals

In the MongoDB shell, you can use forward slashes /pattern/ to define a regular expression. This allows you to perform pattern matching on string fields without explicitly calling the operator.

// Find users whose name starts with "R" db.users.find({ "name": /^R/ }) // Find users whose name contains "java" (case-insensitive) db.users.find({ "name": /java/i })

Common Regex Anchors

Anchors allow you to specify exactly where in the string the match should occur:

  • ^ (Caret): Matches the beginning of the string.
  • $ (Dollar): Matches the end of the string.

💡 Quick Beginner Tip

Regex queries can be slower than standard equality checks. For the best performance, try to use "prefix" expressions (starting with ^) whenever possible, as MongoDB can utilize indexes more effectively for these types of searches!

More MongoDB Tutorials from Ram N Java:

MongoDB Regular Expression (Regex) - Pattern matching with $options Example - Part2 | MongoDB

🚀 Master MongoDB Searching with Ram N Java!

Ready to unlock the full potential of your database queries? Subscribe now for high-quality, beginner-friendly tech tutorials that make complex MongoDB operations like Regex and $options simple to master!

🔔 SUBSCRIBE FOR FREE NOW

Powering Up Text Search with MongoDB $options

Regular expressions are incredibly powerful for finding patterns, but search needs to be flexible. In this guide, we dive into the $options parameter, which allows you to fine-tune your Regex queries. The most common use case? Making your searches case-insensitive.

What is the "i" Option?

By default, MongoDB searches are case-sensitive. If you search for "Gu", it won't find "gu" or "GU". To fix this, we use the i flag within the $options field. This tells MongoDB to ignore the case and return all matches.

Real-World Example: Employee Search

Imagine you have an employee collection and you want to find everyone whose name starts with "gu". Here is how the query looks when you want to capture both "Gupta" and "gupta":

// Finding names starting with "gu" (case-insensitive) db.employee.find({   "empName": { "$regex": "^gu", "$options": "i" } })

With vs. Without $options

When you run the query without the i option, MongoDB is strict. It will only return documents that match your casing exactly. Adding the i option is essential for building user-friendly search bars where users might not care about capitalization.

💡 Quick Beginner Tip

While case-insensitive searching is great for usability, it can be slightly slower on massive datasets. For the best performance, try to combine your Regex with other indexed fields to narrow down the search results first!

More MongoDB Mastery from Ram N Java:

Saturday, 14 November 2020

MongoDB Regular Expression (Regex) with Examples - Part1 | MongoDB Tutorial for Beginners

🚀 Master Modern Databases with Ram N Java!

Ready to search your data like a professional? Subscribe now for high-quality, beginner-friendly tech tutorials that make complex MongoDB queries and Regex operations simple to master!

🔔 SUBSCRIBE FOR FREE NOW

Getting Started with MongoDB Regular Expressions (Regex)

Standard queries are perfect for matching exact values, but in the real world, you often need to find data based on patterns. Whether you're building a search bar or filtering logs, Regular Expressions (Regex) are your best friend. In MongoDB, the $regex operator gives you incredible flexibility to perform string matching.

What is a Regular Expression?

A Regular Expression is a sequence of characters that forms a search pattern. Instead of looking for an exact match like "John", you can look for any name that starts with "Jo", ends with "n", or contains the letter "o".

How to Use $regex in MongoDB

The basic syntax for using the $regex operator is straightforward. You specify the field you want to search and the pattern you're looking for. This is part one of our series where we cover the essential building blocks.

// Basic Regex query structure db.collection.find({   "fieldName": { "$regex": "your_pattern" } })

Key Benefits for Beginners

  • Flexibility: You don't need to know the exact value to find the document.
  • Power: Use special characters to represent "any character" or "start of string".
  • Practicality: Essential for implementing search features in your web or mobile apps.

💡 Quick Beginner Tip

While Regex is very powerful, it can be resource-intensive if used on very large collections without care. Always try to pair your Regex queries with other filters whenever possible to keep your database running fast!

Continue Your MongoDB Journey:

Friday, 26 October 2018

The regular expression in Spring Expression Language SpEL [Annotation] | Spring Tutorial

Master Spring & Java Development!

Subscribe to Ram N Java for clean, beginner-friendly coding guides!

🔔 Subscribe to Ram N Java

Overview: Regex with Spring Expression Language (SpEL)

The Spring Expression Language (SpEL) provides powerful evaluation capabilities, including built-in pattern matching using regular expressions. This allows you to evaluate strings against complex patterns dynamically at application startup or bean initialization.

In this guide, you will learn how to evaluate regular expressions directly using SpEL and inject the resulting boolean verification flag into your Spring beans using the @Value annotation.

Understanding the 'matches' Operator

SpEL introduces the intuitive matches keyword to perform regular expression checks directly within expression definitions.

  • Pattern Syntax: The syntax follows the format 'inputString' matches 'regexPattern'.
  • Boolean Output: If the string matches the specified pattern, SpEL evaluates to true; otherwise, it resolves to false.
  • Validation Scenarios: Ideal for validating formatted strings like email addresses, phone numbers, or zip codes during bean setup.

Configuring Pattern Matching with @Value

You can annotate your component's fields or setter methods to evaluate regex patterns automatically:

  1. Annotation Declaration: Annotate a boolean field with @Value("#{customer.email matches '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}'}").
  2. Dynamic Evaluation: Spring inspects the bean property, runs the regex match, and assigns the boolean outcome directly to your field.

Recommended Next Videos from Ram N Java


Click here to watch on Youtube:
https://www.youtube.com/watch?v=yHnJW78Wm78&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge:

The regular expression in Spring Expression Language SpEL [Annotation] | Spring Tutorial

The regular expression in Spring Expression Language SpEL [Annotation] | Spring Tutorial

The regular expression in Spring Expression Language SpEL [Annotation] | Spring Tutorial

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0%20http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ram.core</groupId>
    <artifactId>SpringDemo</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>SpringDemo</name>
    <url>http://maven.apache.org</url>

    <properties>
        <spring.version>5.0.5.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <!-- Spring 5 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>
</project>

Email.java

package com.ram.model;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("email")
public class Email
{

    @Value("ram@yahoo.com")
    private String emailId;

    @Value("100")
    private String contentId;

    public String getEmailId()
    {
        return emailId;
    }

    public void setEmailId(String emailId)
    {
        this.emailId = emailId;
    }

    public String getContentId()
    {
        return contentId;
    }

    public void setContentId(String contentId)
    {
        this.contentId = contentId;
    }

    @Override
    public String toString()
    {
        return "Email [emailId=" + emailId + ", contentId=" + contentId + "]";
    }

}

Employee.java

package com.ram.model;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("employee")
public class Employee
{
    @Value("10")
    private int id;

    @Value("Peter")
    private String name;

    private String digitRegEx = "\\d+";

    private String emailRegEx = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)"
            + "*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    @Value("#{email.emailId matches employee.emailRegEx}")
    private String isValidEmail;

    @Value("#{email.contentId matches employee.digitRegEx}")
    private String isValidContentId;

    public int getId()
    {
        return id;
    }

    public void setId(int id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public String getDigitRegEx()
    {
        return digitRegEx;
    }

    public void setDigitRegEx(String digitRegEx)
    {
        this.digitRegEx = digitRegEx;
    }

    public String getEmailRegEx()
    {
        return emailRegEx;
    }

    public void setEmailRegEx(String emailRegEx)
    {
        this.emailRegEx = emailRegEx;
    }

    public String getIsValidEmail()
    {
        return isValidEmail;
    }

    public void setIsValidEmail(String isValidEmail)
    {
        this.isValidEmail = isValidEmail;
    }

    public String getIsValidContentId()
    {
        return isValidContentId;
    }

    public void setIsValidContentId(String isValidContentId)
    {
        this.isValidContentId = isValidContentId;
    }

    @Override
    public String toString()
    {
        return "Employee [id=" + id + ", name=" + name + ", isValidEmail="
                + isValidEmail + ", isValidContentId=" + isValidContentId + "]";
    }

}

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.3.xsd">


    <context:component-scan base-package="com.ram" />

</beans>

App.java

package com.ram.core;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ram.model.Employee;
import com.ram.model.Email;

public class App
{
    public static void main(String[] args)
    {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");

        System.out.println("---------------------------------------");

        Email email = (Email) context.getBean("email");
        System.out.println(email + "\n");

        Employee employee = (Employee) context.getBean("employee");
        System.out.println(employee);
    }

}

Output

Sep 21, 2018 9:44:02 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@736e9adb: startup date [Fri Sep 21 09:44:02 IST 2018]; root of context hierarchy
Sep 21, 2018 9:44:02 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
---------------------------------------
Email [emailId=ram@yahoo.com, contentId=100]

Employee [id=10, name=Peter, isValidEmail=true, isValidContentId=true]

Click the below link to download the code:
https://sites.google.com/site/ramj2eev2/java_basics/SpringDemo_Spring%20EL_Regular_exp_Annotation.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/javaee/tree/master/Spring_2018/SpringDemo_Spring%20EL_Regular_exp_Annotation

Bitbucket Link:
https://bitbucket.org/ramram43210/spring/src/41b19a6ea5ff82d0f409d467c69dd68cdbbf4a93/Spring_2018/SpringDemo_Spring%20EL_Regular_exp_Annotation/?at=master

See also:

  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Spring Tutorial
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Cooking Tutorial
  • Thursday, 25 October 2018

    The regular expression in Spring Expression Language SpEL [XML] | Spring Tutorial

    Master Spring & Java Development!

    Subscribe to Ram N Java for clean, beginner-friendly coding guides!

    🔔 Subscribe to Ram N Java

    Overview: Regex Matching in SpEL via XML

    The Spring Expression Language (SpEL) provides powerful evaluation features directly inside XML configuration files. One particularly useful feature is dynamic pattern verification using regular expressions (Regex), allowing you to evaluate string properties right when the Spring container initializes your beans.

    In this guide, you will learn how to check string patterns and inject boolean evaluation results using SpEL within an XML configuration file.

    Understanding the 'matches' Operator

    SpEL features the built-in matches keyword to validate whether a string complies with a regular expression pattern.

    • Syntax: Evaluated inside value expressions: #{'targetString' matches 'regexPattern'} or referencing a bean property like #{customer.email matches 'pattern'}.
    • Boolean Output: If the string satisfies the regular expression pattern, the expression returns true; otherwise, it resolves to false.
    • Direct Bean Property Injection: The resulting true/false value can be directly injected into a boolean field of another bean.

    Configuring SpEL Regex in XML

    Inside your Spring bean configuration XML file, you define the property element using the value attribute:

    1. Define Target Bean: Set up the bean containing the string property you want to test (for example, a user profile or contact details).
    2. Evaluate in Property Tag: <property name="validEmail" value="#{customer.email matches '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}'}" />
    3. Automatic Container Evaluation: When loading your ApplicationContext, Spring executes the expression and sets the boolean flag automatically.

    Recommended Next Videos from Ram N Java


    Click here to watch on Youtube:
    https://www.youtube.com/watch?v=YZW20ugQ3o8&list=UUhwKlOVR041tngjerWxVccw

    Click the below Image to Enlarge:
    The regular expression in Spring Expression Language SpEL [XML] | Spring Tutorial

    The regular expression in Spring Expression Language SpEL [XML] | Spring Tutorial

    The regular expression in Spring Expression Language SpEL [XML] | Spring Tutorial
    pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0%20http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.ram.core</groupId>
        <artifactId>SpringDemo</artifactId>
        <packaging>jar</packaging>
        <version>1.0-SNAPSHOT</version>
        <name>SpringDemo</name>
        <url>http://maven.apache.org</url>

        <properties>
            <spring.version>5.0.5.RELEASE</spring.version>
        </properties>

        <dependencies>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>3.8.1</version>
                <scope>test</scope>
            </dependency>

            <!-- Spring 5 dependencies -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
        </dependencies>
    </project>

    Email.java

    package com.ram.model;

    public class Email
    {

        private String emailId;
        private String contentId;

        public String getEmailId()
        {
            return emailId;
        }

        public void setEmailId(String emailId)
        {
            this.emailId = emailId;
        }

        public String getContentId()
        {
            return contentId;
        }

        public void setContentId(String contentId)
        {
            this.contentId = contentId;
        }

        @Override
        public String toString()
        {
            return "Email [emailId=" + emailId + ", contentId=" + contentId + "]";
        }

    }

    Employee.java

    package com.ram.model;

    public class Employee
    {
        private int id;
        private String name;

        private String digitRegEx = "\\d+";

        private String emailRegEx = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)"
                + "*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

        private String isValidEmail;
        private String isValidContentId;

        public int getId()
        {
            return id;
        }

        public void setId(int id)
        {
            this.id = id;
        }

        public String getName()
        {
            return name;
        }

        public void setName(String name)
        {
            this.name = name;
        }

        public String getDigitRegEx()
        {
            return digitRegEx;
        }

        public void setDigitRegEx(String digitRegEx)
        {
            this.digitRegEx = digitRegEx;
        }

        public String getEmailRegEx()
        {
            return emailRegEx;
        }

        public void setEmailRegEx(String emailRegEx)
        {
            this.emailRegEx = emailRegEx;
        }

        public String getIsValidEmail()
        {
            return isValidEmail;
        }

        public void setIsValidEmail(String isValidEmail)
        {
            this.isValidEmail = isValidEmail;
        }

        public String getIsValidContentId()
        {
            return isValidContentId;
        }

        public void setIsValidContentId(String isValidContentId)
        {
            this.isValidContentId = isValidContentId;
        }

        @Override
        public String toString()
        {
            return "Employee [id=" + id + ", name=" + name + ", isValidEmail="
                    + isValidEmail + ", isValidContentId=" + isValidContentId + "]";
        }

    }

    applicationContext.xml

    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd">


        <bean id="email" class="com.ram.model.Email">
            <property name="emailId" value="ram@yahoo.com"></property>
            <property name="contentId" value="100"></property>
        </bean>

        <bean id="employee" class="com.ram.model.Employee">
            <property name="id" value="10"></property>
            <property name="name" value="Peter"></property>
            <property name="isValidEmail" value="#{email.emailId matches employee.emailRegEx}"></property>
            <property name="isValidContentId"
                value="#{email.contentId matches employee.digitRegEx}"></property>
        </bean>

    </beans>

    App.java

    package com.ram.core;

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;

    import com.ram.model.Employee;
    import com.ram.model.Email;

    public class App
    {
        public static void main(String[] args)
        {
            ApplicationContext context = new ClassPathXmlApplicationContext(
                    "applicationContext.xml");

            System.out.println("---------------------------------------");

            Email email = (Email) context.getBean("email");
            System.out.println(email + "\n");

            Employee employee = (Employee) context.getBean("employee");
            System.out.println(employee);
        }

    }

    Output

    Sep 23, 2018 10:31:59 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
    INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@736e9adb: startup date [Sun Sep 23 10:31:59 IST 2018]; root of context hierarchy
    Sep 23, 2018 10:31:59 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
    ---------------------------------------
    Email [emailId=ram@yahoo.com, contentId=100]

    Employee [id=10, name=Peter, isValidEmail=true, isValidContentId=true]

    Click the below link to download the code:
    https://sites.google.com/site/ramj2eev2/java_basics/SpringDemo_Spring%20EL_Regular_exp_XML.zip?attredirects=0&d=1

    Github Link:
    https://github.com/ramram43210/javaee/tree/master/Spring_2018/SpringDemo_Spring%20EL_Regular_exp_XML

    Bitbucket Link:
    https://bitbucket.org/ramram43210/spring/src/41b19a6ea5ff82d0f409d467c69dd68cdbbf4a93/Spring_2018/SpringDemo_Spring%20EL_Regular_exp_XML/?at=master

    See also:


  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Spring Tutorial
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Cooking Tutorial
  • Tutorials