How to Use Regex in Java

How to Use Regex in Java

In this article, we will learn about Java Regex, and how to use Regex with examples in Java. Java regex is also known as Java Regular Expression.

Introduction

In this article, we will learn about Java Regex, and how to use Regex with examples in Java. Java regex is also known as Java Regular Expression.

What is Regex in Java?

Regular expressions or Java Regex is an API built to define string patterns that can be used to read, alter, and delete data. For pattern matching with the regular expressions, Java offers java.util.regex bundle.

In other words, a regular expression is a special sequence of characters that helps us match or find other strings using a special syntax held in a pattern that is used to search, edit, or manipulate text and data.

java.util.regex package

This provides regular expressions with three classes and a single interface. The classes Matcher and Pattern are usually used in standard Java language.

The complete program of regex package is listed below.

import java.util.regex.Pattern;  
  
public class RegexPackageExample {  
    public static void main(String args[]) {  
        System.out.println(Pattern.matches(".y", "toy"));  
        System.out.println(Pattern.matches("s..", "sam"));  
        System.out.println(Pattern.matches(".a", "mia"));  
    }  
} 

The above program generates the following output.

PatternSyntaxException class

PatternSyntaxException is a unresolved exception object which means a syntax error in a normal speaking pattern.

The complete program of Showing the PatternSyntaxException class example is listed below.

import java.util.regex.Pattern;  
  
public class PatternSyntaxExceptionExample {  
    public static void main(String... args) {  
        String regex = "["; // invalid regex  
        Pattern pattern = Pattern.compile(regex);  
    }   
} 

The above program generates the following output.

Note

In the above example program, we use the invalid syntax of regex. So, when we run the program it generates the PatternSyntaxException: Unclosed character class near index 0;

java.util.regex.Matcher;

A Matcher entity is a motor that interprets the template against an input string and executes operations of play. Matcher doesn't describe any public builders, as the class Template. By calling the matcher method) (you get a Matcher object on a Pattern object.

Methods of Matcher class

public boolean matches()

The matches method is used to check the pattern string is matches with matcher string or not. It returns the boolean value. If the string matches, it returns true otherwise false. It does not take any argument. It does not throw any exception.

Syntax

public boolean matches();

The complete program of java.util.regex.Matcher.matches() method is listed below.

import java.util.regex.*;  
public class MatchesMethodExample {  
    public static void main(String[] args) {  
        boolean result;  
        // Get the string value to be checked  
        String value1 = "CsharpCorner";  
  
        // Create a pattern from regex  
        Pattern pattern = Pattern.compile(value1);  
  
        // Get the String value to be matched  
        String value2 = "CsharpC";  
  
        // Create a matcher for the input String  
        Matcher matcher = pattern.matcher(value2);  
  
        // Get the current matcher state  
        System.out.println("result : " + matcher.matches());  
    }  
} 

The above program generates the following output.

public int start() Method

The start() method is used to get the start subsequence index. public int start() method does not take any argument. It returns the index of the first character matched 0. If the operation is failed it throws IllegalStateException.

Syntax

public int start();

The complete program of java.util.regex.Matcher.start() method is listed below.

import java.util.regex.*;  
  
public class StartMethodExample {  
    public static void main(String[] args) {  
  
        // Get the string value to be checked  
        String value1  = "CsharpCorner";  
  
        // Create a pattern from regex  
        Pattern pattern = Pattern.compile(value1);  
  
        // Get the String value to be matched  
        String value2 = "Csharp";  
        // Create a matcher for the input String  
        Matcher matcher = pattern.matcher(value2);  
  
        // Get the current matcher state  
        MatchResult result = matcher.toMatchResult();  
        System.out.println("Current Matcher: " + result);  
  
        while (matcher.find()) {  
            // Get the first index of match result  
            System.out.println(matcher.start());  
        }  
    }  
}

The above program generates the following output.

public boolean find() Method

The find method is used to find the next subsequence of the input sequence that finds the pattern.  It returns a boolean value. If the input string matches then it returns true otherwise returns false. This method does not take any argument. This method does not throw any exception.

Syntax

public boolean find()

The complete program of java.util.regex.Matcher.find() method is listed below.

import java.util.regex.*;  
public class FindMethodExample {  
    public static void main(String args[]) {  
        // Get the regex to be checked  
        String value = "CsharpCorner";  
        String value1 = "Java Programming";  
  
        // Create a string from regex  
        Pattern pattern = Pattern.compile(value);  
        Pattern pattern1 = Pattern.compile(value1);  
  
        // Get the String for matching  
        String matchString = "CsharpCorner";  
        String matchString1 ="Java";  
  
        // Create a matcher for the String  
        Matcher match = pattern.matcher(matchString);  
        Matcher match1 = pattern.matcher(matchString1);  
        //find() method  
        System.out.println(match.find());  
        System.out.println(match1.find());  
  
    }  
} 

The above program generates the following output.

public boolean find(int start) Method

The find(int start) method is used to find the next subsequence of the input sequence that finds the pattern, according to the given argument. It returns a boolean value. This method does not take any argument. This method throws IndexOutOfBoundException if the given argument is less then zero or greater then the length of the string.

Syntax

public boolean find(int start);

The complete program of java.util.regex.Matcher.find() method is listed below.

import java.util.regex.*;  
  
public class FindMethodExample2 {  
    public static void main(String args[]) {  
        // Get the regex to be checked  
        String value = "CsharpCorner";  
        String value1 = "Java Programming";  
  
        // Create a string from regex  
        Pattern pattern = Pattern.compile(value);  
        Pattern pattern1 = Pattern.compile(value1);  
  
        // Get the String for matching  
        String matchString = "CsharpCorner";  
        String matchString1 = "Java";  
  
        // Create a matcher for the String  
        Matcher match = pattern.matcher(matchString);  
        Matcher match1 = pattern.matcher(matchString1);  
        //find() method  
        System.out.println(match.find(3));  
        System.out.println(match1.find(6));  
  
    }  
} 

The above program generates the following output.

public int end() Method

The end method is used to get the offset after the last match of the character is done. This method doesn't take any argument. this method throws IllegalStateException if the operation fails.

Syntax

public int end()

The complete program example of java.util.regex.Matcher.end() is listed below.

import java.util.regex.*;  
public class endMethodExample {  
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
        Pattern p=Pattern.compile("Hello C#Corner");  
        Matcher m=p.matcher("Hello C#Corner");  
        if(m.matches())  
            System.out.println("Both are matching till "+m.end()+" character");  
        else  
            System.out.println("Both are not matching"+m.end());  
    }  
} 

The above program generates the following output.

java.util.regex.Pattern

A Pattern object is a compiled representation of a regular expression. There are no Template level public designers. To construct a template, you first need to invoke one of its public static compiles (methods which subsequently return a Template item, which acknowledges a regular expression as the first statement

It is the compiled form of a regular expression and is used to describe the Regex engine template.

Methods of Pattern class

static Pattern compile(String regex)

The compile() method is used to match a text from a regular expression(regex) pattern. If the operation is failed it returns false otherwise true. This method takes a pattern string value as the argument.

Syntax

static Pattern compile(String regex)

The complete program of the java.util.regex.pattern.compile();

import java.util.regex.Matcher;  
import java.util.regex.Pattern;  
  
public class CompileMethodExample {  
  
    public static void main(String args[]) {  
  
        // Get the string value to be checked  
        Pattern p = Pattern.compile(".o");  
          
        //Matcher string for  
        Matcher m = p.matcher("to");  
        boolean m1 = m.matches();  
        System.out.println(m1);  
    }  
}  

The above program generates the following output.

public boolean matches(regex, String)

The matches() method is used to check the given string matches the given regular expression or not. This method returns the boolean value true if the string matches the regex otherwise it returns false.  If the syntax is invalid then this method throws PatternStateException.

This method takes two arguments.

  • regex- This argument is the regular expression value which has to check from the string.
  • String- This string value has to check from the regex through the matches() method.

The complete program of the public boolean matches(regex, String) method is listed below.

import java.util.regex.Pattern;  
  
public class PatternClassMatchesMethod {  
    public static void main(String args[]) {  
        System.out.println(Pattern.matches("[bad]", "abcd"));  
        System.out.println(Pattern.matches("[as]", "a"));  
        System.out.println(Pattern.matches("[ass]", "asssna"));  
    }  
} 

The above program generates the following output.

Summary

In this article, we learned about Java Regular Expression(regex) in Java Programming Language and the varoius methods of regex.

Thank for reading and keep visiting!

Guide to Python Programming Language

Guide to Python Programming Language

Guide to Python Programming Language

Description
The course will lead you from beginning level to advance in Python Programming Language. You do not need any prior knowledge on Python or any programming language or even programming to join the course and become an expert on the topic.

The course is begin continuously developing by adding lectures regularly.

Please see the Promo and free sample video to get to know more.

Hope you will enjoy it.

Basic knowledge
An Enthusiast Mind
A Computer
Basic Knowledge To Use Computer
Internet Connection
What will you learn
Will Be Expert On Python Programming Language
Build Application On Python Programming Language

Learn Java Programming | Java Complete Tutorial for Beginners | Simpliv

Learn Java Programming | Java Complete Tutorial for Beginners | Simpliv

This program on Java programing from Simpliv’s experts uses Java and an Integrated Development Environment (IDE). Just download this, with their help of course, and open your way to hundreds of lines of source code, and hundreds of lines of comments. That is some Java programming learning!

Description
Taught by a Stanford-educated, ex-Googler, husband-wife team
This course will use Java and an Integrated Development Environment (IDE). Never fear, we have a detailed video on how to get this downloaded and set up.
Hundreds of lines of source code, and hundreds of lines of comments - just download and open in your IDE!
A Java course for everyone - accessible yet serious, to take you from absolute beginner to an early intermediate level

Let’s parse that.

This is a Java course for everyone. Whether you are a complete beginner (a liberal arts major, an accountant, doctor, lawyer) or an engineer with some programming experience but looking to learn Java - this course is right for you.
The course is accessible because it assumes absolutely no programming knowledge, and quickly builds up using first principles alone
Even so, this is a serious Java programming class - the gradient is quite steep, and you will go from absolute beginner to an early intermediate level
The course is also quirky. The examples are irreverent. Lots of little touches: repetition, zooming out so we remember the big picture, active learning with plenty of quizzes. There’s also a peppy soundtrack, and art - all shown by studies to improve cognition and recall.
What's Covered:

Programming Basics: What programming is, and a carefully thought-through tour of the basics of any programming. Installing and setting up an IDE and writing your first program
The Object-Oriented Paradigm: Classes, Objects, Interfaces, Inheritance; how an OO mindset differs from a functional or imperative programming mindset; the mechanics of OO - access modifiers, dynamic dispatch, abstract base classes v interfaces. The underlying principles of OO: encapsulation, abstraction, polymorphism
Threading and Concurrency: A deep and thorough study of both old and new ways of doing threading in Java: Runnables, Callables, Threads, processes, Futures, Executors.
Reflection, Annotations: The how, what and why - also the good and bad
Lambda Functions: Functional constructs that have made the crossover into the mainstream of Java - lambda functions, aggregate operators.
Modern Java constructs: Interface default methods; properties and bindings too. Also detailed coverage of Futures and Callables, as well as of Lambda functions, aggregation operators. JavaFX as contrasted with Swing.
Packages and Jars: The plumbing is important to understand too.
Language Features: Serialisation; why the Cloneable interface sucks; exception handling; the immutability of Strings; the Object base class; primitive and object reference types; pass-by-value and pass-by-object-reference.
Design: The MVC Paradigm, Observer and Command Design Patterns.
Swing: Framework basics; JFrames, JPanels and JComponents; Menus and menu handling; Trees and their nuances; File choosers, buttons, browser controls. A very brief introduction to JavaFX.
Programming Drills (code-alongs, with source code included)

Serious stuff:
A daily stock quote summariser: scrapes the internet, does some calculations, and outputs a nice, formatted Excel spreadsheet.
A News Curation app to summarise newspaper articles into a concise email snippet using serious Swing programming
Simple stuff:
Support with choosing a programming environment; downloading and setting up IntelliJ.
Simple hello-world style programs in functional, imperative and object-oriented paradigms.
Maps, lists, arrays. Creating, instantiating and using objects, interfaces
Who is the target audience?

Yep! Folks with zero programming experience - liberal arts majors, doctors, accountants, lawyers
Yep! Engineering students from non-CS majors looking to learn fairly serious programming
Nope! Experienced Java programmers - this class will be boring for you:)
Yep! Computer Science students or software engineers with no experience in Java, but experience in Python, C++ or even C#. You might need to skip over some bits, but in general the class will still have new learning to offer you :-)
Basic knowledge
No prior programming experience needed:)
The class will make use of Java and an IDE - never fear, we have a detailed video to walk you through the process of setting this up
What will you learn
Write Java programs of moderate complexity and sophistication (at an early to middling intermediate level)
Understand Object-Oriented programming concepts at the level where you can have intelligent design conversations with an experienced software engineer
Manage concurrency and threading issues in a multi-threaded environment
Create and modify files (including Excel spreadsheets) and download content from the internet using Java
Use Reflection, Annotations, Lambda functions and other modern Java language features
Build serious UI applications in Swing
Understand the Model-View-Controller paradigm, the Observer and Command Design patterns that are at the heart of modern UI programming
Gain a superficial understanding of JavaFX and Properties and Bindings
Understand the nuances of Java specific constructs in serialisation, exception-handling, cloning, the immutability of strings, primitive and object reference types
To continue:

Free Java Programming for Complete Beginners in 250 Steps | Simpliv

Free Java Programming for Complete Beginners in 250 Steps | Simpliv

Free Java Programming for Complete Beginners in 250 Steps

Description
We love Programming. Our aim with this course is to create a love for Programming.

Java is one of the most popular programming languages. Java offers both object oriented and functional programming features.

We take an hands-on approach using a combination of JShell(An awesome new feature in Java 9) and Eclipse as an IDE to illustrate more than 200 Java Coding Exercises, Puzzles and Code Examples.

In more than 250 Steps, we explore the most important Java Programming Language Features

Basics of Java Programming - Expressions, Variables and Printing Output
Java Operators - Java Assignment Operator, Relational and Logical Operators, Short Circuit Operators
Java Conditionals and If Statement
Methods - Parameters, Arguments and Return Values
Object Oriented Programming - Class, Object, State and Behavior
Basics of OOPS - Encapsulation, Abstraction, Inheritance and Polymorphism
Basics about Java Data Types - Casting, Operators and More
Java Built in Classes - BigDecimal, String, Java Wrapper Classes
Conditionals with Java - If Else Statement, Nested If Else, Java Switch Statement, Java Ternary Operator
Loops - For Loop, While Loop in Java, Do While Loop, Break and Continue
Immutablity of Java Wrapper Classes, String and BigDecimal
Java Dates - Introduction to LocalDate, LocalTime and LocalDateTime
Java Array and ArrayList - Java String Arrays, Arrays of Objects, Primitive Data Types, toString and Exceptions
Introduction to Variable Arguments
Basics of Designing a Class - Class, Object, State and Behavior. Deciding State and Constructors.
Understanding Object Composition and Inheritance
Java Abstract Class and Interfaces. Introduction to Polymorphism.
Java Collections - List Interface(ArrayList, LinkedList and Vector), Set Interface (HashSet, LinkedHashSet and TreeSet), Queue Interface (PriorityQueue) and Map Interface (HashMap, HashTable, LinkedHashMap and TreeMap() - Compare, Contrast and Choose
Generics - Why do we need Generics? Restrictions with extends and Generic Methods, WildCards - Upper Bound and Lower Bound.
Functional Programming - Lambda Expression, Stream and Operations on a Stream (Intermediate Operations - Sort, Distinct, Filter, Map and Terminal Operations - max, min, collect to List), Functional Interfaces - Predicate Interface,Consumer Interface, Function Inteface for Mapping, Method References - static and instance methods
Introduction to Threads and MultiThreading - Need for Threads
Implementing Threads - Extending Thread Class and Implementing Runnable Interface
States of a Thread and Communication between Threads
Introduction to Executor Service - Customizing number of Active Threads. Returning a Future, invokeAll and invokeAny
Introduction to Exception Handling - Your Thought Process during Exception Handling. try, catch and finally. Exception Hierarchy - Checked Exceptions vs Unchecked Exceptions. Throwing an Exception. Creating and Throwing a Custom Exception - CurrenciesDoNotMatchException. Try with Resources - New Feature in Java 7.
List files and folders in Directory with Files list method, File walk method and find methods. Read and write from a File.
Who is the target audience?

You want to learn Programming
You are a beginner and want to explore Java further
You want to learn the basics of Object Oriented Programming with Java
You want to learn the basics of Functional Programming with Java
Basic knowledge
Connectivity to Internet to download Java 9 and Eclipse.
We will help you install Eclipse and Java 9
Oracle Solaris or 64 bit Microsoft Windows or Linux or macOS
Java 9 does NOT work on 32 bit Microsoft Windows! You would need a 64 bit Microsoft Windows if you would want to use Windows.
What will you learn
You will learn how to think as a Java Programmer
You will learn how to start your journey as a Java Programmer
You will learn the basics of Eclipse IDE and JShell
You will learn to develop awesome object oriented programs with Java
You will solve a wide variety of hands-on exercises with Java
You will learn the basics of programming - variables, choosing a data type, conditional execution, loops, writing great methods, breaking down problems into sub problems and implementing great Exception Handling
You will learn the basics of Object Oriented Programming - Intefaces, Inheritance, Abstract Class and Constructors
You will learn the important concepts of Object Oriented Programming - Abstraction, Inheritance, Encapsulation and Polymorphism
You will learn to do basic functional programming with Java
You will learn the basics of MultiThreading - with Executor Service
You will learn about a wide variety of Collections - List, Map, Set and Queue Interfaces
To continue: