Reputation: 29051
Is there any convenient way to fake raw strings in VS2012? (I'm thinking using a preprocessor macro, but am open to suggestions.)
My use case is a fairly long, but static, list of regular expressions, that are nearly unreadable with all of the escaped \
's.
The alternative to having code that looks like this:
p[TokenType::Comment ] = "(/\\*([^*]|[\\r\\n]|(\\*+([^*/]|[\\r\\n])))*\\*+/)|(//.*)";
p[TokenType::Float ] = "[0-9]+\\.[0-9^(A-Za-z)]*";
p[TokenType::Integer ] = "[0-9]+";
p[TokenType::String ] = "\\\"([^\\\"\\\\\\\\]|\\\\\\\\.)*\\\"";
p[TokenType::Identifier ] = "[a-zA-Z_][a-zA-Z0-9_]*";
p[TokenType::Operator ] = "\\^|\\*|\\/|\\+|\\-|\\=";
p[TokenType::BinaryOperator] = "(\\=\\=)|(\\+\\=)|(\\-\\=)|(\\*\\=)|(\\/\\=)";
p[TokenType::WhiteSpace ] = "\\s+";
p[TokenType::EndOfStatement] = ";";
p[TokenType::ListStart ] = "\\(";
p[TokenType::ListDelimiter ] = "\\,";
p[TokenType::ListEnd ] = "\\)";
p[TokenType::BlockStart ] = "\\{";
p[TokenType::BlockEnd ] = "\\}";
(which is just plain ugly, and difficult to maintain.)
I've found is to put everything in a text file and load it at runtime, but I'd rather not have to distribute that. Suggestions?
Upvotes: 0
Views: 120
Reputation: 498
A simple answer is: put strings into resources, then load them at run time.
Upvotes: 2
Reputation: 126887
Write a code generator that takes the input file in a simple format and outputs the escaped .cpp
, then add it to your pre-build steps.
In Python, assuming an input file like this:
Comment=(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|(//.*)
Float=[0-9]+\.[0-9^(A-Za-z)]*
the whole thing would boil down to something like:
def c_escape(s):
result = ''
for c in s:
if not (32 <= ord(c) < 127) or c in ('\\', '"'):
result += '\\%03o' % ord(c)
else:
result += c
return result
import sys
inFile = open(sys.args[1])
outFile = open(sys.args[2], 'w')
for l in inFile:
idx = l.find('=')
k,v = l[0:idx], c_escape(l[idx+1:])
outFile.write('p[TokenType::%s]="%s";\n' % (k, v)
Upvotes: 5