Showing posts with label RegEx. Show all posts
Showing posts with label RegEx. Show all posts

Wednesday, March 28, 2018

Can you use Interactive C# for Regular Expressions?

Yes, you can. However you have to reference the Regex class (System.Text.RegularExpressions) as shown in this image.


After this you can use its objects and you have intellisense to provide you help in coding.


The Syntax for using RegularExpressions is:

Match match = Regex.Match(InputStr, Pattern, RegexOptions)

You set up a pattern and you test your Pattern against the InputStr you set up to see if there is a match.

Let me shown a very simple example (the example is run in Interactive C# in Visual Studio Community 2017). Make sure you have already used using System.Text.RegularExpressions before executing these statements:

In the above, the InputStr is 'Jayaram' and the Pattern is shown above. You need to type each line and hit Enter. It is somewhat slow.
In the above case, a match was found for the first lower-case letter in the InputStr.

Here is another example:

The match is for the first upper-case letter in the string.

Here is an example for 2 adjacent numbers in the string:

Only one of the blocks there is a match. Same pattern but different InputStr.




Monday, October 3, 2016

Can you filter the contents of a text file with PowerShell?

In order to work with text files you should know where the text file is stored (saved) in your directory. Once you have the file reference; if you just want to open the file, you could call Notepad from within Powershell like this (type this in the powershell prompt and it will open the file (I am using a file in one of my directories):

PS C:\Users\Jayaram> notepad.exe "C:\Users\Jayaram\Documents\Blog2016\HodentekPlus2016\NoblePrizeMedicine2016.txt"

However if you want to see the contents of the file on your dos screen and filter it you need to use the Get-Content commandlet as shown:


Once you have a file you can search through the text as shown here (here I am looking for all instances of 2016:

PS C:\Users\Jayaram> get-content  "C:\Users\Jayaram\Documents\Blog2016\HodentekPlus2016\NoblePrizeMedicine2016.txt"|Select-String -Pattern "2016"

Yoshinori Ohsumi gets the 2016 Noble Prize for Medicine
Physics 10/4 2016
Chemistry 10/5/2016
Peace 10/6/2016
Literature 10/29/2016


Note: RegEx has enough power to search for almost anything.