正则表达式与Ruby的先行(Regular Expressions with lookahead i

2019-09-16 15:52发布

我现在正则表达式的战斗在字符串中的号码前替换所有的逗号。 然后,正则表达式必须忽略所有后续逗号。 我一直在胡闹上rubular了大约一个小时,不能完全似乎得到的东西的工作。

测试字符串...

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

所需的输出...

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

因此沿线的东西...

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

给你一些背景,我在做一个小刮sideproject。 我收集元件基本上是逗号分隔以两位数岁开始。 然而有时那里有一个标题前述可能包含逗号岁。 为了保持我成立了后来的结构,我需要更换逗号标题。

后尝试开始堆栈溢出的回答...

我仍然有一些问题。 别笑,但这里是从屏幕的实际行刮造成的问题,多数民众赞成...

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:" 

Answer 1:

码:

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



Answer 2:

事实并非如此短暂,但是,似乎解决你的任务:

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

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

    before = $1
    tail = $2

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

print str


文章来源: Regular Expressions with lookahead in Ruby