我目前的正则表达式之战是替换字符串中数字之前的所有逗号。然后,正则表达式必须忽略所有后续逗号。 我已经在 rubular 上搞砸了大约一个小时,似乎无法让某些东西起作用。
测试字符串...
'this is, a , sentence33 Here, is another.'
期望的输出...
'this is comma a comma sentence33 Here, is another.'
所以类似的东西
...testString.gsub(/,*dd/,"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:"
代码:
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
不是那么短,但是,似乎解决了你的任务:
str = 'this is, a , sentence33 Here, is another.'
str = str.match(/(.*)(d+.*)/) do
before = $1
tail = $2
before.gsub( /,/, 'comma' ) + tail
end
print str