Format string using regular expression

  • Thread starter Thread starter MikeTI
  • Start date Start date
M

MikeTI

Nov 15, 2009

Hi all

I want to format a string using regular expression.

Regular Expression "[A-Z/]{4} [0-9]{6} [0-9]{1}"
Should format "AAAA1234567" as "AAAA 123456 7"

I have tried Regex.Replace

Dim mRegEx As Regex
Dim mRegString As String = ""

mRegEx = New Regex("[A-Z/]{4} [0-9]{6} [0-9]{1}")
mRegString = Regex.Replace("AAAA1234567", "[A-Z/]{4} [0-9]{6}
[0-9]{1}", "")
MsgBox(mRegString)

Thanks
Mike TI
 
MikeTI said:
I want to format a string using regular expression.

Regular Expression "[A-Z/]{4} [0-9]{6} [0-9]{1}"
Should format "AAAA1234567" as "AAAA 123456 7"

I have tried Regex.Replace

Dim mRegEx As Regex
Dim mRegString As String = ""

mRegEx = New Regex("[A-Z/]{4} [0-9]{6} [0-9]{1}")
mRegString = Regex.Replace("AAAA1234567", "[A-Z/]{4} [0-9]{6}
[0-9]{1}", "")
MsgBox(mRegString)

You need to code that as follows:

Dim mRegEx As Regex
Dim mRegString As String = ""

mRegEx = New Regex("([A-Z/]{4})([0-9]{6})([0-9])")
mRegString = mRegEx.Replace("AAAA1234567", "$1 $2 $3")
Console.WriteLine(mRegString)

The $n refer to the groups in the regular expression that are enclosed
in parentheses.
 
It works.

Thanks.
Mike TI

Martin Honnen said:
MikeTI said:
I want to format a string using regular expression.

Regular Expression "[A-Z/]{4} [0-9]{6} [0-9]{1}"
Should format "AAAA1234567" as "AAAA 123456 7"

I have tried Regex.Replace

Dim mRegEx As Regex
Dim mRegString As String = ""

mRegEx = New Regex("[A-Z/]{4} [0-9]{6} [0-9]{1}")
mRegString = Regex.Replace("AAAA1234567", "[A-Z/]{4} [0-9]{6}
[0-9]{1}", "")
MsgBox(mRegString)

You need to code that as follows:

Dim mRegEx As Regex
Dim mRegString As String = ""

mRegEx = New Regex("([A-Z/]{4})([0-9]{6})([0-9])")
mRegString = mRegEx.Replace("AAAA1234567", "$1 $2 $3")
Console.WriteLine(mRegString)

The $n refer to the groups in the regular expression that are enclosed in
parentheses.
 
Back
Top