开发者

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 t开发者_开发知识库ext 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, i.e. “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 (e.g. 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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜