special characters in replace function

眉间皱痕 提交于 2019-12-11 06:35:07

问题


GREL replace function expects 3 strings, or a string, a regex and a string. In the 3rd string used for replacement, some characters have a special behavior : \, \, \t, \n, \', \" and maybe some other combinations. \ does nothing, or an error \ is interpreted as \ \t is interpreted as a tab character \n is interpreted as a new line \" is interpreted as " \' is interpreted as '

Ex : "abab".replace('b',"\") -> "Parsing error at offset 19: Missing number, string, identifier, regex, or parenthesized expression"

"abab".replace ('b',"\t") -> a a

I suppose it has something to do with Java... Is there other special combinations? Is it documented somewhere on the wiki?


回答1:


In a string, the backslash (\) has a special meaning. It basically says that the following character should not be considered in its usual sense. This is why the string "t" is just the letter t, but "\t" means a tab.

This escape character is also used to include quotation marks in a string. The string 'L'alouette', for example, will trigger an error, since it contains a quotation mark of the same type as the one surrounding the string. The problem can be avoided by escaping the inner ' : 'L\'alouette' (or by using double quotes: "l'alouette")

In your example, OpenRefine understands that you want to escape the second quotation mark ("\") and considers that your string is not finished. The correct syntax, in this case, would be to escape the \ itself : "abab".replace('b', "\\")

List of special characters

| Special characters | Display               |
|--------------------|-----------------------|
| \'                 | Single quotation mark |
| \"                 | Double quotation mark |
| \\                 | Backslash             |
| \t                 | Tab                   |
| \b                 | Backspace             |
| \r                 | Carriage return       |
| \f                 | Formfeed              |
| \n                 | Newline               |


来源:https://stackoverflow.com/questions/52456548/special-characters-in-replace-function

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