Matching Literal Text

Ben is a regular expression. Because it is plain text, it may not look like a
regular expression, but it is.

So, here goes:

TEXT

Hello, my name is Ben.

REGEX

Ben

RESULT

Hello, my name is Ben.

How Many Matches?

The default behavior of most regular expression engines is to return just the first match. If we want to return all matches than we can use g (global) flag.

Handling Case Sensitivity

Regular expressions are case sensitive, so Ben will not match ben. However, most regex implementations also support matches that are not case sensitive. JavaScript users, for example, can specify the optional i flag to force a search that is not case sensitive. 

Matching Any Characters

The regular expressions thus far have matched static text only—rather anticlimactic,indeed. Next we’ll look at matching unknowncharacters. The . character (period,or full stop) matches any one character.

Here is an example:
TEXT
sales1.xls
orders3.xls
sales2.xls
sales3.xls
apac1.xls
europe2.xls
na1.xls
na2.xls
sa1.xls

REGEX

sales.

RESULT

sales1.xls
orders3.xls
sales2.xls
sales3.xls
apac1.xls
europe2.xls
na1.xls
na2.xls
sa1.xls

so . is used to match any character. 

If we want to get two or more characters then we can use that number of dots or periods.

For example

Text

Rat.he
Ratt.he
Rattt.he
Rattee.he

Regex

Rat..

Result

Rat.he
Ratt.he
Rattt.he
Rattee.he

Also if want to exactly match . then we can use \ (escape charaters) to define it.

For Example

Text

Rat.he
Ratt.he
Rattt.he
Rattee.he

Regex

Rat.\.

Result

Rat.he
Ratt.he
Rattt.he
Rattee.he

Summary

Regular expressions,also called patterns, are strings made up of characters. These characters may be literal (actual text) or metacharacters (special characters with special meanings), and  you learned how to match a single character using both literal text and metacharacters. . matches any character. \ is used to escape characters and to start special character sequences.
 

Categories: Regex

faltutech

Pursuing MCA from YMCA University, Faridabad

Leave a Reply

Your email address will not be published. Required fields are marked *

Read previous post:
regex regular expression (FaltuTech.club)
Introduction to Regular Expressions (Regex)

Regular expressions and the regular expression language have been around for many years. Regular expression experts have long been armed...

Close