Format string using regular expression

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
 
M

Martin Honnen

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.
 
M

MikeTI

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top