user3757155
user3757155

Reputation: 15

How to delete chars in string by position only?

I need a regex search & replace pair that will delete 'n' characters from a string, starting at some definable location. For example, to delete 3 characters starting at position 5. In that case the string

AAA. 01 Data From July

would become

AAA. Data from July

(Don't know if I've started counting at the right spot re 0/1. That's one reason I need a general solution.)

It can be assumed that the strings will be long enough to support the operation, but it would be very good if it does nothing on too short a string.

The app I'm working within has a VBScript regex engine. I've searched the web for every variation on this request I can imagine but even with all the regex advice out there this seems to be new. I thought it would be almost cookbook. I've also tried doing it myself but can't figure out how to position the engine at the capture point.

Upvotes: 1

Views: 165

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200273

With fixed positions/lengths you could also use the Mid function:

Function RemoveSubstring(str, start, length)
  RemoveSubstring = Mid(str, 1, start - 1) & Mid(str, start + length)
End Function

Upvotes: 0

dognose
dognose

Reputation: 20889

Assuming, your app contains the options to configure the replacement, you could use a backreference-replacement like this:

(.{5}).{3}(.*)
  • (.{5}) matches the first 5 characters
  • .{3} consumes the next 3 characters
  • (.*) matches all remaining charaters

The backreference-replacement \1\2 (depending on application \\1\\2 or $1$2) will concatenate match group one and two, so basically removing the three characters of the second expression, because they are not forming a match group.

https://regex101.com/r/aC8fQ9/2

Upvotes: 1

Related Questions