简体   繁体   中英

How do I know which are the first characters before “/”? asp.net vb.net

I have a string like that:

Dim temp As String = "Batch 634239100A/45 pcs booked out by vladut moraru on 10/15/2015"

Or

Dim temp As String = "Batch 322.3/4 pcs booked out by vladut moraru on 10/15/2015"

Or

Dim temp As String = "Batch 322/3/4 pcs booked out by vladut moraru on 10/15/2015"

I want to display 322/3/

Batch is : 322/3/
PCS is : 4

I want to display just : 322/3/ of all string

I thought I'd find 322/3/4 and then to give it split after the last / and find value from before the / , but how?

The easiest thing to do would be use a RegularExpression , but there are limitations to this, especially as you're also including a date in the string.

If the numbers are ALWAYS in the format of NNN/NNN/NN and they will appear before any date then this will work...

Dim regExMatch As System.Text.RegularExpressions.Match
regExMatch = System.Text.RegularExpressions.Regex.Match(myString, "(\d{3}/\d{3})/(\d{2})")
If regExMatch.Success Then
    Dim batch As String = regExMatch.Groups(1).Value
    Dim pcs As String = regExMatch.Groups(2).Value
End If

The regex (\\d{3}/\\d{3})/(\\d{2}) breaks down as...

  • ( Create a capture group
  • \\d{3} look for 3 numeric digits (0-9)
  • / look for that character
  • \\d{3} look for 3 numeric digits (0-9)
  • ) Close and store the capture group
  • / look for that character
  • ( Create a capture group
  • \\d{2} look for 2 numeric digits (0-9)
  • ) Close and store the capture group

(Note, in ASP.NET is it not required to escape the / character... in most other regex parsers it is necessary.)


If you don't need the pcs to be retrieved, then remove the 2nd capture group (so it looks like (\\d{3}/\\d{3})/\\d{2} )... but then you would also need to remove the regExMatch.Groups(2).Value otherwise you'll get an exception.


If you need to check for a variable number of digits then use the format of \\d{3,5} which would mean a minimum of 3 and a maximum of 5 numeric digits.


UPDATE - based on the new information provided by the OP.

Use this expression: "batch (.+)/(\\d+) pcs"

regExMatch = System.Text.RegularExpressions.Regex.Match(myString, "batch (.+)/(\d+) pcs", 
               System.Text.RegularExpressions.RegexOptions.IgnoreCase)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM