[英]Regular Expressions with lookahead in Ruby
我當前的正則表達式之爭是在字符串中的數字前替換所有逗號。 然后正則表達式必須忽略所有后續逗號。 我已經在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:"
碼:
testString = 'this is, a , sentence33 Here, is another.';
result = testString.gsub(/\,(?=.*\d)/, 'comma');
print result;
輸出:
this iscomma a comma sentence33 Here, is another.
測試:
不是那么短暫,但似乎解決了你的任務:
str = 'this is, a , sentence33 Here, is another.'
str = str.match(/(.*)(\d+.*)/) do
before = $1
tail = $2
before.gsub( /,/, 'comma' ) + tail
end
print str
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.