Home > OS >  Remove a pattern from a string limited by delimiter or end of the string
Remove a pattern from a string limited by delimiter or end of the string

Time:09-26

colleagues.

I'm stuck on a simple question: I have the connection string: Server=35.237.131.8,14333; Database=Online LIMS; Trusted_Connection = No; User Id = LimsUser; Password = lims42; Pooling=False; MultipleActiveResultSets=False; DRIVER = SQL SERVER; LastSection = false

And I want to delete the section DRIVER. It's very simple, but there is one issue: this section can be at the end of the string: "Server=35.237.131.8,14333; Database=Online LIMS; Trusted_Connection = No; User Id = LimsUser; Password = lims42; Pooling=False; MultipleActiveResultSets=False; DRIVER = SQL SERVER" and delimiter ';' is missing in this case.

My current regex (?<DriverSection>DRIVER.*?;*)(?=;|$) match the section at the end of the string and in the middle, but in the middle it does not include the separator ';', so this character is keeping in the string after deletion: Server=35.237.131.8,14333; Database=Online LIMS; Trusted_Connection = No; User Id = LimsUser; Password = lims42; Pooling=False; MultipleActiveResultSets=False;; LastSection = false

And I have two ';' characters in the string, what is wrong. So my question: is it possible to match both cases by one regex?

My current regex is available here: https://regex101.com/r/OSZKtA/1

Thanks everybody.

CodePudding user response:

check this out

(?<DriverSection>DRIVER.*?;*)(?<=;|$)

https://regex101.com/r/2CG6iw/1

CodePudding user response:

You can use a match with a negated character class, and then optionally match the trailing ;

\b(?<DriverSection>DRIVER\s*=[^;]*;?)
  • \b A word boundary to prevent a partial word match
  • (?<DriverSection> Named group DriverSection
    • DRIVER\s*= Match DRIVER, optional whitespace chars and then =
    • [^;]* Match 1 chars optional chars other than ;
    • ;? Optionally match ;
  • ) Close the named group

See a regex demo.

CodePudding user response:

Match non-semicolons, which naturally stop at end of string anyway:

(?<=DRIVER = )[^;] 

See live demo.

  • (?<=DRIVER = ) is a look behind, meaning the previous characters must be "DRIVER = "
  • [^;] is a negated character class and means any character except a semicolon
  • means one or more

If your language/tool (not stated in question) does not support look arounds, you can still use the "non-semicolon" approach if you match the variable name too:

DRIVER = [^;] 

See live demo.

  • Related