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

强颜欢笑 提交于 2019-12-23 19:57:36

问题


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 f ("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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3874408/what-should-an-escape-character-do-if-the-following-character-doesnt-need-escap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!