import Foundation
let pattern = #"[`\\]|\${"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
// source https://stackoverflow.com/a/75688937/6404439
import React from 'react';
import SyntaxHighlighter from 'react-syntax-highlighter';
import { a11yDark } from 'react-syntax-highlighter/dist/esm/styles/hljs';
const CodeBlock: React.FC<{ codestring: string }> = ({ codestring }) => {
return (
<SyntaxHighlighter
language="javascript"
style={a11yDark}
showLineNumbers>
{codestring}
</SyntaxHighlighter>
);
};
function App() {
var code = `function $initHighlight(block, cls) {
try {
if (cls.search(/\bno\-highlight\b/) != -1)
return process(block, true, 0x0F) +
\` class="\${cls}"\`;
} catch (e) {
/* handle exception */
}
for (var i = 0 / 2; i < classes.length; i++) {
if (checkCondition(classes[i]) === undefined)
return /\d+[\s/]/g;
}
return 0xA;
}
export $initHighlight;`;
return (
<div className="w-1/2 bg-blue-700">
<CodeBlock codestring={code} />
</div>
);
}
export default App;
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #"\\$&"#
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