Home > Mobile >  Regex to convert hyphenated object id keys not surrounded by quotes in vscode
Regex to convert hyphenated object id keys not surrounded by quotes in vscode

Time:11-26

I've got a load of imported data but the main id keys of the object aren't surrounded in quotation marks and so aren't valid javascript.

Here's a sample of some of the data I have:


8ae3fcef-d1f5-43e4-9df0-b1861117c2f2: {
      id: "8ae3fcef-d1f5-43e4-9df0-b1861117c2f2",
      randomNumber: null,
      openSearchId: null,
      facilityId: "dd4bf527-d395-40df-a079-6ed9c73272d9",
      spaceId: "9672350c-8b0e-4a99-a836-16a8f1e11667",
      bucket: "ist1-tenant-1af9e2a9-41c8-45c4-9d0d-fe25a1d9b988",
      key: "8ae3fcef-d1f5-43e4-9df0-b1861117c2f2/7ae3fcef-d1f5-43e4-9df0-b1861117c2f2_1662040410090952011.jpeg"
},
8dc3d....... etc

What I figure I need to do is target something that is:

  • 36 characters long
  • contains numbers, letters and hyphens
  • not starting or ending with quotation marks
  • has a colon afterwards.

I want to use find and replace in vscode to target and replace what i need.

I've tried to check that the first character isn't " and that all 36 characters are letters, numbers or a hyphen. Closest i've come so far is this (it looks like it checks the first letter and then the following ones so I had to put 35 for it to not break completely):

[^" ][A-Za-z0-9\-]{35}

However that also gives me all of the ones (and other unrelated values) that are surrounded by "". I've also checked various other threads but i can't figure it out, can anyone offer any guidance?

Thanks

CodePudding user response:

If the lookbehind assertion worked for you, you might make it a bit more specific matching at least a minimum number of hyphens.

(?<!\S)(?=[a-f0-9-]{36}:)[a-f0-9] (?:-[a-f0-9] ){2,}

Explanation

  • (?<!\S) Assert a whitespace boundary to the left
  • (?=[a-f0-9-]{36}:) Assert 36 chars a-f 0-9 - followed by a colon
  • [a-f0-9] (?:-[a-f0-9] ){2,} Match at least a certain amount of hyphens like 2, 3...

In the replacement use can use the full match surrounded by double quotes:

"$0"

See a regex demo.

CodePudding user response:

Assuming your id strings are at the beginning of the line you can use this regex search:

^([A-Za-z0-9\-]{36}):

Use this for replace:

"$1":

I am not familiar with vscode, you might need to tweak the $1 that references the capture group 1

  • Related