Regex help please...

tunderin

Member
Licensed User
Longtime User
The matcher in the code below comes from Erel's Mailparser found here

B4X:
   Dim headers As String 
      Dim filename As String
      Dim m As Matcher
      
      headers="Content-Type: application/octet-stream;     name=Claim_M312764.ini Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename=Claim_M312764.ini "
      
      m = Regex.Matcher2("filename=\s*q([^q]+)q".Replace("q", QUOTE), Regex.CASE_INSENSITIVE, headers)
      If m.Find Then filename = m.Group(1) Else filename = "attachment"
      
      Msgbox(filename,"Attachment name is")

It fails to find the filename "Claim_M312764.ini" in the headers

Regex is a weakness of mine and though I have been reading tutorials about it, I still don't know enough to fix it myself.

Any help would be appreciated...
 

melamoud

Active Member
Licensed User
Longtime User
the code look for filename="......" but in the string headers in the code there is no ""
you either need to add them before and after the filename= part
or change the regexp to not look for them
in this case the string ends with a space if you know this is the case you can change the regexp to be:
B4X:
m = Regex.Matcher2("filename=\s*([^\s]+)\s", Regex.CASE_INSENSITIVE, headers)
 
Upvote 0

melamoud

Active Member
Licensed User
Longtime User
or if the filename can have space in it you need to do something like this
B4X:
m = Regex.Matcher2("filename=\s*q(.*?)\s*^".Replace("q", QUOTE), Regex.CASE_INSENSITIVE, headers)

where the ^ show the end of the line, but this works only if the filename attribute comes at the end of the line, there are many other tricks but you need to know how to end the search, what for sure end the filename
 
Upvote 0

Mark Read

Well-Known Member
Licensed User
Longtime User
Hello Tunderin,

I cannot try this code at present but something along the lines of this should work.

B4X:
Dim Pattern as string
Dim CharsToLoose as int

Pattern="filename=[\w-]+\.ini"
CharsToLoose=9  'Chop first 9 chars from string, adjust as required

m = Regex.Matcher(Pattern, headers)
filename=m.Match.SubString2(CharsToLoose,m.Match.Length)

Hope this helps
Regards
Mark
 
Upvote 0

tunderin

Member
Licensed User
Longtime User
Thank you!

Thanks to you both - this solves my problem.

This is a great forum...
 
Upvote 0

Similar Threads

Top