在ruby中用`\\`替换`\`

时间:2015-06-14 16:38:33

标签: ruby gsub

我尝试用\替换所有出现的\\。这是我的第一次尝试:

> puts '\\'.gsub('\\', '\\\\')
\
当我看到输出时,我很惊讶。经过一些实验,我终于能够做到我想要的代码:

> puts '\\'.gsub('\\', '\\\\\\')
\\

为什么第一段代码没有工作?为什么我需要六个反斜杠?

3 个答案:

答案 0 :(得分:3)

'\\'.gsub('\\', '\\\\')

当替换发生时,替换字符串'\\\\' Regexp 引擎传递,\\\替换。替换字符串最后为'\\',单个反斜杠。

将任何单个bachslach替换为double的自动方式是使用:

str.gsub(/\\/, '\\\\\\\\\')  # 8 backslashes!

答案 1 :(得分:2)

您也可以使用Regexp.escape来逃避\

puts '\\'.gsub('\\', Regexp.escape('\\\\'))

答案 2 :(得分:1)

稍短一点

#include<iostream>
#include<string>

using namespace std;

struct stack
{
    int inf;
    stack* link;
} *gStart; // don't need p at all start renamed to avoid collisions

void push(stack * & start)
{
    stack *p; //just holds a temporary no need to pass
    int s; // same as above

    while (!(cin >> s)) // read and test the input        
    { // bad input. Clear stream and prompt
        cin.clear(); 
        cout << "nice try, wiseguy. Gimmie an int!" << endl;
    }

    p = new stack();
    p->inf = s;
    p->link = start;
    start = p;

    cout << "pushed " << start->inf << endl;
}

void pop(stack *& start)
{
    stack *p; //no need to pass in
    if (start != NULL)
    { // don't pop list if list empty
        cout << "popped " << start->inf << endl;
        p = start;
        start = p->link;
        delete p;
    }
    else
    {
        cout << "stack empty" << endl;
    }
}

int main()
{
    // there is no need for start to be global. It could just as easily be allocated here.
    string thing;

    cin >> thing;
    while (thing != "end")
    {
        if (thing == "push")
        {
            push(gStart);
        }
        else if (thing == "pop")
        {
            pop(gStart);
        }

        cin >> thing;
    }
    return 0;
}