2

我目前的正则表达式战斗是替换字符串中数字之前的所有逗号。然后,正则表达式必须忽略所有以下逗号。我已经在 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:" 
4

2 回答 2

4

代码:

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

于 2012-04-19T22:30:05.280 回答
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
于 2012-04-19T22:25:08.150 回答