PowerShell and Regex Problem

Ask your PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 15 years and 1 month old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

PowerShell and Regex Problem

Post by jvierra »

Regex is a very powerful tool for processing text. The "[RegEx"] type is native to PowerShell. PowerShell supports the -match and -replace operations on strings and elsewhere. However....

In C# we can do teh following:

Code: Select all

string resultString = Regex.Replace("02/22/1997","d{1,2})/(?<day>d{1,2})/(?<year>d{2,4})b">b(?<month>d{1,2})/(?<day>d{1,2})/(?<year>d{2,4})b","${day}-${month}-${year}");

The out come of this is "22/02/1997" which reverses thet day and month. This is a fairly standard Euro/US translation.

In PowerShell the method is called and works but oes not convert the values and it seems to not detect any match cases.

Try this:

Code: Select all

$r=[regex]""
$r.Replace( "02/22/1997","d{1,2})/(?<year>d{2,4})b","${day}-${month}-${year'><strong>b(?<month>d{1,2})/(?<day>d{1,2})/(?<year>d{2,4})b","${day}-${month}-${year}")

This will produce an error on the translation patern.

Try this way:

Code: Select all

$r=[regex]""
$r.Replace( "02/22/1997","b(?<month>d{1,2})/(?<day>d{1,2})/(?<year>d{2,4})b","${day}${month}${year}")
This removes the dashes and eliminates the error but does not chage teh value in the output.

And this:

Code: Select all

$r=[regex]""
$r.Replace( "02/22/1997","b(?<month>d{1,2})/(?<day>d{1,2})/(?<year>d{2,4})b","${day}${month}${year}")

Produce this: // as output. It is getting the replacement call but the groups are not being populated.
Any ideas?

It looks as if the method being called is not the correct one. How can we coerce it to use the correct method?

If we can use this from PoSH then many more translations are possible without using delegates and a simple RegEx test harness can be built in PoSH that will allow for simple building and testing of expressions which might be useful at times.







jvierra2009-02-22 13:36:47
This topic is 15 years and 1 month old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked