正则表达式,在Ruby中具有前瞻性

时间:2012-04-19 22:02:04

标签: ruby regex ruby-1.9.2 regex-lookarounds

我目前的正则表达式之争是在字符串中的数字前替换所有逗号。然后正则表达式必须忽略所有后续逗号。我已经在rubular上拧了大约一个小时,看起来似乎无法正常工作。

测试字符串......

'this is, a , sentence33 Here, is another.'

期望的输出......

'this is comma a comma sentence33 Here, is another.'

这就像......

testString.gsub(/\,*\d\d/,"comma")

为了给你一些背景知识,我正在做一些有点狡猾的侧面项目。我收集的元素主要以逗号分隔,从两位数年龄开始。然而,有时候可能包含逗号的年龄前的标题。为了保留我稍后设置的结构,我需要替换标题中的逗号。

尝试堆叠溢出后的答案......

我还有一些问题。不要笑,但这里是屏幕抓取导致问题的实际线......

statsString =     "              23,  5'9\",  140lb,  29w,                        Slim,                 Brown       Hair,             Shaved Body,              White,    Looking for       Friendship,    1-on-1 Sex,    Relationship.   Out      Yes,SmokeNo,DrinkNo,DrugsNo,ZodiacCancer.      Versatile,                  7.5\"                    Cut, Safe Sex Only,     HIV      Negative, Prefer meeting at:Public Place.                   PerformerContact  xxxxxx87                                                   This user has TURNED OFF his IM                                     Send Smile      Write xxxxxx87 a message:" 

首先对所有这些片段添加'xx',这样我的逗号过滤就可以在所有情况下使用,包括在年龄之前有和没有文本的那些。接下来是实际修复。输出低于......

statsString = 'xx, ' + statsString

statsString = statsString.gsub(/\,(?=.*\d)/, 'comma');

 => "xxcomma               23comma  5'9\"comma  140lbcomma  29wcomma                        Slimcomma                 Brown       Haircomma             Shaved Bodycomma              Whitecomma    Looking for       Friendshipcomma    1-on-1 Sexcomma    Relationship.   Out      YescommaSmokeNocommaDrinkNocommaDrugsNocommaZodiacCancer.      Versatilecomma                  7.5\"                    Cutcomma Safe Sex Onlycomma     HIV      Negativecomma Prefer meeting at:Public Place.                   PerformerContact  xxxxx87                                                   This user has TURNED OFF his IM                                     Send Smile      Write xxxxxxx87 a message:" 

2 个答案:

答案 0 :(得分:2)

<强> 代码:

testString = 'this is, a , sentence33 Here, is another.';
result = testString.gsub(/\,(?=.*\d)/, 'comma');
print result;

<强> 输出:

this iscomma a comma sentence33 Here, is another.

<强> 测试:

http://ideone.com/9nt1b

答案 1 :(得分:1)

不是那么短,但似乎可以解决你的任务:

str = 'this is, a , sentence33 Here, is another.'

str = str.match(/(.*)(\d+.*)/) do

    before = $1
    tail = $2

    before.gsub( /,/, 'comma' ) + tail
end

print str
相关问题