匹配字符串

时间:2015-08-06 18:14:48

标签: ruby string

我有以下字符串(joe也可以是sallysusan):

test. 456. CREATED-BY-joe

我想删除字符串的开头,直到"CREATED-BY",并留下joe。我该怎么做呢?

5 个答案:

答案 0 :(得分:1)

我会做这样的事情:

string = 'test. 456. CREATED-BY-joe'
string.match(/CREATED-BY-(\S+)\z/)[1]
#=> "joe"

答案 1 :(得分:1)

.row {
    position: relative;
    display: table;
    width: 99%;
}

.col {
    display: table-cell;
    width: 72%;
    position: relative;
    vertical-align: middle;
    color: #03274B; 
    padding: 5px;
    border-bottom: 1px solid black;
    border-left: 1px solid black;
    font-family: ‘Lucida Sans Unicode’, ‘Lucida Grande’, sans-serif;
}

.col2 {
    display: table-cell;
    width: 27%;
    position: relative;
    color: #03274B;
    background-color: #DCDCDC;
    overflow: scroll;
    padding: 5px;
    border: 1px solid black;
    font-family: ‘Lucida Sans Unicode’, ‘Lucida Grande’, sans-serif;
}

答案 2 :(得分:0)

如何使用split代替正则表达式?

> 'test. 456. CREATED-BY-joe'.split('CREATED-BY-').last
=> "joe"

答案 3 :(得分:0)

还有两种方式:

s = "test. 456. CREATED-BY-joe"

s[/CREATED-BY-\K.+/]
  #=> "joe"

s[s.rindex('CREATED-BY-')+'CREATED-BY-'.size..-1]
  #=> "joe"

答案 4 :(得分:0)

我使用String's []方法,它可以采用正则表达式并返回特定的捕获:

str = 'test. 456. CREATED-BY-joe'
str[/CREATED-BY-(\S+)/, 1]
# => "joe"

(\S+)是神奇的部分,它告诉正则表达式引擎返回不是空格的所有内容。如果字符串超出joe,则

test. 456. CREATED-BY-joe,MODIFIED-BY-fred

有问题,但这很容易解决。