Wednesday, January 25, 2012

Part-3: Text Manipulation in PowerShell using .StartsWith() and EndsWith() methods

 

Part-1: http://newdelhipowershellusergroup.blogspot.com/2012/01/part-1-text-manipulation-in-powershell.html | using Trim(),TrimEnd(),TrimStart()

Part-2: http://newdelhipowershellusergroup.blogspot.com/2012/01/part-2-text-manipulation-in-powershell.html | ToUpper(),ToLower()

Hi,

Today we are going to use .StartsWith() and .EndsWith() methods to play with our text.

we are using the same text which we used in previous posts and saving the text in a variable $text

$text = "The Quick brown fox jumps over the lazy dog"

24-01-2012 15-14-58 

Lets start.

.StartsWith()

This test that check that the string start with the character which we specified in .StartWith() and it give result is Boolean, the result is either “True” or “false”

lets check if our text start with “The Quick”

$text.StartsWith("The Quick")

the result is “True” , which means yes our text is start with “The Quick”

24-01-2012 15-21-40

NOTE: By default the the text which we specified in  StartsWith() and EndsWith() are case sensitive. Not getting my point ? let me show you.

this is our default text. “T” in The and “Q” in Quick is uppercase.

24-01-2012 15-14-58 

this time i type all lower case character in .StartsWith() method and lets see the result

$text.StartsWith("the quick")

and this time result is false. You need take care of it if you are going to use these methods in your scripts.

24-01-2012 15-30-58

lets compare.. I hope everything is clear now.

24-01-2012 15-32-45

How to fix it ???

to make these methods make case-insensitive add ,1 after the text. This ,1 is in igonecase  switch which is Boolean, so 1 means is case-insensitive is ON

$text.StartsWith("the quick",1)

Bingo !!! now our condition is true.. :)

24-01-2012 15-43-47 

Lets See the comparison chart. The result are in the front of you…

24-01-2012 15-45-23 

.EndsWith()

lets check if out text ends with “lazy dog”

$text.EndsWith("lazy dog")

The result is “True” which means our text ends with “lazy dog”

24-01-2012 15-48-59

as i mentioned before that the text in these Methods take as case sensitive. in our current string “lazy dog” is in lower case let try to search with “Lazy Dog”

$text.EndsWith("Lazy Dog")

as expected the result is “False”

24-01-2012 15-57-30

lets make it case-insensitive by ON the IgnoreCase switch

$text.EndsWith("Lazy Dog",1)

Bingoo !!! its true now ….

24-01-2012 16-09-31

want to see the comparison? I bet you want…

In the screenshot you can see the original text and the methods with ignorecase and without ignorecase switch

24-01-2012 16-11-05

Thanks

Aman Dhally

Aman Dhally

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.