Hello everyone!!π
Are you confused with the titleπ ? Do you also stay away from regular expressions? Do you use google while solving regex problems? Not after reading this article!π
C'mon, let's learn it together.π€
CONTENTS
Why Regular Expressions?
Regex(Regular Expressions) is used to define various types of string patterns which can be used for manipulating, searching, or editing a string. It can be used in all types of text search and text replace operations. Simply, a regular expression is a sequence of characters that helps us to match or find strings.
As we are now aware of regex, let's see how to write it.π€©
Cheatsheets
Matching Symbols
Note: [^regex]
and ^regex
are totally different.
Meta Characters
Quantifiers
How to write regular expressions?
We should write a regular expression pattern in such a way that it satisfies the required output. Many of them feel regex is hard because of this. So, let's solve some examples to understand this more clearly.
disclaimer: I am using java methods in solutions below. If you are willing to use other languages just check with the regular expression, which is our main goal.π
- Question-1: Given string is "I love Hashnode. It is a wonderful platform." Write a matching regular expression that split the string into tokens.
As we take only words as tokens we have to removeString s="I love Hashnode. It is a wonderful platform." ; s=s.replaceAll("[^\\w]", " ");
.
after each sentence. So, we used [^\\w] inreplaceAll()
to replace all characters except [a-zA-Z_0-9] with a white-space. Now, to split them into tokens we doπ
Here, we are scanning for a token until a white-space occurs. We identified white spaces using [\\s]. Since there can be a sequence of more than one white spaces we also used aString[] str=s.split("[\\s]+");
+
.
Output: [I, love, Hashnode, It, is, a, wonderful, platform]
- Question-2: Given a string "I l1ove Hashn7ode. It is 3a wond5erful pla4tform.". Our aim is to print only numbers from this string.
Our aim is to get numbers right? So, I am replacing everything with a white-space expect 0-9 using [^0-9].String s="I l1ove Hashn7ode. It is 3a wond5erful pla4tform."; s=s.replaceAll("[^0-9]", " ");
s=s.trim(); String[] str=s.split("[\\s]+");
- Why we used
trim()
?
- Why we used
trim()
is used to remove trailing and leading spaces. After replacing alphabets with a white-space, we get trailing spaces because of I
in " I love Hashnode". Since trailing spaces cannot be identified with [\\s]+ we used trim()
.
Output: [1, 7, 3, 5, 4]
That's all peopleπ. Now, we can write any regex patterns in any language by using these cheat sheets.
Say bye-bye to google!π