Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with regex

Status
Not open for further replies.

maxxpress

Programmer
Mar 17, 2013
2
TW
Hi all,
I'm useless with regex - please help!

I need to extract the last digit from the string - but here's the catch if the digit is 0001 I want only to capture the 1 not the leading 0's so far i have

Regex r= new Regex(@"^(.*?)(\d+)(\D*)$");

but that doesn't work for when i have 0001.

any ideas?

 
I am not good at regex either. when i have to use it, I use a free tool called Expresso. It has a UI that helps you build and test regex expressions.
 


I'm not a big user either. I played around with it and here's what I came up with:

Code:
Dim testString As String = "A string ending in a number 0001"
Dim pattern As String = "\d{1}$"
Dim r As Regex = New Regex(pattern, RegexOptions.IgnoreCase)
Dim m As Match = r.Match(testString)
Dim lastNumberInString As Integer = -1

If m.Success Then
    lastNumberInString = CInt(m.Value)
End If
Debug.Print(lastNumberInString)

The pattern "\d{1}$" is basically looking at the string from the end ($), looking for a single (\d{1}) digit. You can change the number to however many digits you would like to match (like 4, although in the example, "0001" would convert to 1 in an integer conversion anyway.)





Mark

"You guys pair up in groups of three, then line up in a circle."
- Bill Peterson, a Florida State football coach
 
hi guys,

i managed to do it by doing

Regex lastNumberPattern = new Regex(@"^(.*?)(([0]+)|([1-9]))?(\d+)(\D*)$");

thanks anyway!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top