开发者

What should an escape character do if the following character doesn't need escaping?

开发者 https://www.devze.com 2023-01-19 03:21 出处:网络
An application I\'m working on has a field where a string can be entered. Special characters in the string cause different things to be inserted when the string is evaluated, but these special charac

An application I'm working on has a field where a string can be entered.

Special characters in the string cause different things to be inserted when the string is evaluated, but these special characters can be preceded by an escape character (a backslash) which cause the special character to be output literally rather than its special meaning.

Think of it as similar to a regular expression: . matches any character but \. matches a dot.

What is the most intuitive thing to happen when the escape character is followed by a character which doesn't need escaping? For example, would it make more sense that:

  1. The escape character "escapes" the literal as itself: \f becomes 开发者_StackOverflowf ("an escaped f")
  2. The escape character isn't an escape character unless it's followed by a special character: \f remains as \f
  3. Error! Throw an exception because the it's invalid to have an escape character not escaping anything

All of these are possible and in my opinion justifiable. But which makes more sense, and which is already most common in other languages?


I'd vote for the first solution. It makes forming strings easy: If you don't know if a character has a special meaning in your context, just escape it. It won't hurt.


Ultimately, the right answer is probably not language-agnostic. In Ada I'd expect option three, because it's largely about strictly enforcing strict rules. In Perl, I'd expect option one or two, because it's much more permissive as a rule.

Since I'm mostly a C++ programmer, I'd vote for option 4: arrange for a function to be called in such a case. The "faulty" sequence is passed to it as a parameter, and it's expected to either return an interpreted result or throw an exception.

If it was a native Windows API, I'd expect something close to the C++ solution, only it would build a chain of functions, starting from the most recently added, and working its way down the chain until a function either returned an interpreted result, or it got to the end of the chain where the default function would throw an exception.

0

精彩评论

暂无评论...
验证码 换一张
取 消