简体   繁体   中英

Regex problems in VB.net, how do I match this?

I never understand how to create regular expressions and now I need one badly. It would be great if someone know how to do this.

I need to match these examples with a regex and then append text before the third comma: Examples:

1.

Örjan,,;Svensson,,,,, and then it continues like this

Needs to become:

Örjan,,;SvenssonNEWTEXTHERE,,,,, and then it continues like this

2.

Patric,The-Man,Black,,,,,,,,, and then it continues like this

Needs to become:

Patric,The-Man,BlackNEWTEXTHERE,,,,,,,,, and then it continues like this

If I would use wildcards to do this it would look like this:

*,*,*,*

And I would like to add text just before the last comma. But I still need the whole string so the text can just be added there I don't want the characters that comes after the added text to disappear.

This is a .CSV contact file btw so you better understand the structure of the text.

Is this possible?

The regular expression for a CSV field, ie “any text not containing comma”, is [^,]* , if you want to skip to the end of the third field, you'll use

[^,]*,[^,]*,[^,]*

Now, if you want to modify the string, you can use something like

Dim str = "Örjan,,;Svensson,,,,, and then it continues like this"
Dim re As New Regex("[^,]*,[^,]*,[^,]*")
Dim pos = re.Match(str).Length

Now you've got the position of where you want to put the additional string in pos , and you can do whatever you want with it.

Note that a CSV file can generally contain fields which contain literal commas and need to be quoted (eg Patric,"The,Man",Black,... ). It may even contain a linebreak, which makes it quite difficult to parse properly, especially with regular expressions (and the code above would not work with such data). Can you be sure your CSV file does not contain quoted fields?

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