import Foundation
let pattern = #"(\w+\s*\n*=\s*\n*)\{\n*\s*`((?:[^`](?!(?:\$\{|\n|(?:'[^`]*"|"[^`]*'))))*)`\n*\s*\}"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
// Match!
<Component1
// Using backticks without utilizing their functionalities
className={`flex justify-center items-center gap-2`}
description={``}
content={
`These backticks are unnecessary`
}
// This is a crime, but I did take it into account
horrendousFormatting
=
{`Please never do something like this`}
/>
// Multiple matches in a single line
<svg width={`100%`} height={`100%`} />
// Cases where this regex won't match:
<Component2
// Non-string property
disabled={isDisabled}
// Quotes/Single quotes with unnecessary brackets
// (I have another regex that's better adapted for this!)
href={"https://regex101.com/library/l9MPcQ"}
// String templating
className={`flex items-center justify-center size-5 ${iconColor}`}
// Escaping BOTH " AND ' IN THE SAME STRING with backticks
title={`This string's backticks are "justified"`}
// Escaping line breaks with backticks
description={
`String with
a line break`
}
// "/'/` mismatch
content={`Yeah this will turn the rest of your file into a string"}
>
{icon}
// No match since this is not a property
{` `}
(Some people do this instead of using )
</Component2>
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #"$1"$2""#
let result = regex.stringByReplacingMatches(in: testString, range: stringRange, withTemplate: substitutionString)
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Swift 5.2, please visit: https://developer.apple.com/documentation/foundation/nsregularexpression