簡體   English   中英

Ruby gsub / regex修飾符?

[英]Ruby gsub / regex modifiers?

我在哪里可以找到關於gsub修飾符的文檔? \\ a \\ b \\ c \\ 1 \\ 2 \\ 3%a%b%c $ 1 $ 2%3等?

具體來說,我正在看這個代碼...... something.gsub(/%u/, unit)你的%u是什么?

首先, %u在ruby正則表達式中沒有什么特別之處:

mixonic@pandora ~ $ irb
irb(main):001:0> '%u'.gsub(/%u/,'heyhey')
=> "heyhey"

Ruby 1.8 regex的權威文檔在Ruby Doc Bundle中:

由斜杠分隔的字符串是正則表達式。 緊接在后一個斜杠之后的字符表示正則表達式的選項。 選項i表示正則表達式不區分大小寫。 選項i表示正則表達式在第一次計算時只執行一次表達式替換。 選項x表示擴展正則表達式,這意味着表達式中允許使用空格和共數。 選項p表示POSIX模式,其中換行被視為普通字符(與點匹配)。

%r / STRING /是正則表達式的另一種形式。

 ^ beginning of a line or string $ end of a line or string . any character except newline \\w word character[0-9A-Za-z_] \\W non-word character \\s whitespace character[ \\t\\n\\r\\f] \\S non-whitespace character \\d digit, same as[0-9] \\D non-digit \\A beginning of a string \\Z end of a string, or before newline at the end \\z end of a string \\b word boundary(outside[]only) \\B non-word boundary \\b backspace(0x08)(inside[]only) [ ] any single character of set * 0 or more previous regular expression *? 0 or more previous regular expression(non greedy) + 1 or more previous regular expression +? 1 or more previous regular expression(non greedy) {m,n} at least m but most n previous regular expression {m,n}? at least m but most n previous regular expression(non greedy) ? 0 or 1 previous regular expression | alternation ( ) grouping regular expressions (?# ) comment (?: ) grouping without backreferences (?= ) zero-width positive look-ahead assertion (?! ) zero-width negative look-ahead assertion (?ix-ix) turns on (or off) `i' and `x' options within regular expression. 

這些修飾符位於封閉組(如果有)內。 (?ix-ix :)在此非捕獲組中打開(或關閉) i' and x'選項。

正則表達式中提供反斜杠表示法和表達式替換。

祝好運!

Zenspider的Quickref包含一個部分,說明可以在regexen中使用哪些轉義序列,以及一個列出由regexp匹配設置的偽變量的部分 在gsub的第二個參數中,您只需使用反斜杠而不是$來編寫變量的名稱,並在應用regexp后將其替換為該變量的值。 如果使用雙引號字符串,則需要使用兩個反斜杠。

使用gsub的塊形式時,您可以直接使用變量。 如果從塊中返回包含例如\\ 1的字符串,則不會被$ 1替換。 只有在使用雙參數形式時才會發生這種情況。

如果你在sub / gsub中使用block,你可以訪問這樣的組:

>> rx = /(ab(cd)ef)/
>> s = "-abcdef-abcdef"
>> s.gsub(rx) { $2 }
=> "cdgh-cdghi"

對於Ruby 1.9的Oniguruma有正則表達式的一個良好的文檔在這里

gsub也是LUA語言中的字符串替換函數。

LUA正則表達式語言中,%u表示大寫字符類。 即它將匹配所有大寫字母。 同樣,%l將匹配小寫。

LUA正則表達式模式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM