简体   繁体   中英

Regex to replace a string that may or may not be quoted

I'm trying to replace all instances of the key INPUT_CSV in a string with a file path that is guaranteed to not have any single or double quotes (or other unsafe characters for paths) within it. However, this file path will be surrounded by double quotes.

The key may be surrounded by double quotes, single quotes, or no quotes at all in the input string. I want to be as flexible as possible, and replace all of those instances with the same, double-quoted file path.

This is how I'm currently doing it:

Dim doubleQuotedCsvFilePath As String = """" & generatedCsvFilePath & """"

scriptStr = scriptStr.Replace("""INPUT_CSV""", doubleQuotedCsvFilePath)
scriptStr = scriptStr.Replace("'INPUT_CSV'", doubleQuotedCsvFilePath)
scriptStr = scriptStr.Replace("INPUT_CSV", doubleQuotedCsvFilePath)

Is there some sort of nifty regex (or possibly some other method) that can do essentially this more succinctly? If this is the best way to do it, I'm fine with that too - just wondering if there is a better way. Thanks!

PS Not a requirement, but if there was some way to make the regex case-insenstive too (so that eg "input_csv" , 'input_CSV' , or INPut_CSV all get replaced), that would be great also. Thanks!

You can use back reference for matching the first quote:

  string scriptStr= "'INPUT_CSV'";
  string pattern = @"(""|'?)INPUT_CSV\1";
  Regex rgx = new Regex(pattern);
  scriptStr = rgx.Replace(scriptStr, doubleQuotedCsvFilePath);

See https://msdn.microsoft.com/en-us/library/thwdfzxy%28v=vs.110%29.aspx

Here is my attempt:

(?i)(['""]?)input_csv\1

(?i) turns on case-insensitive search, then we capture an optional single or double quote into a capturing group, match the input_csv string and then check if there is the same closing quote as the opening one.

VB.NET:

Dim doubleQuotedCsvFilePath As String = """" & "InPuT_CsV" & """"
Dim scriptStr As String
Dim m As Regex = New Regex("(?i)(['""]?)input_csv\1")
scriptStr = m.Replace(doubleQuotedCsvFilePath, "$1INPUT_CSV$1")

C#:

var doubleQuotedCsvFilePath = "\"InPuT_CsV\"";
var scriptStr = string.Empty;
var m = new Regex(@"(?i)(['""]?)input_csv\1");
scriptStr = m.Replace(doubleQuotedCsvFilePath, "$1INPUT_CSV$1");

Output:

"INPUT_CSV"

DISCLAIMER : Only use it if you are not re-inventing the wheel with a CSV parser.

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