簡體   English   中英

如何捕獲字符串中的連續字符

[英]How to capture consecutive characters in a string

我有一個字符串'aabaaa' 如何使用正則表達式捕獲連續字符,以便獲得類似以下內容的信息?

[['aa'], ['b'], ['aaa']]

我對確定每個字符連續出現多少次感興趣。

出於好奇:

紅寶石> = 2.4

'aabaaa'.each_char.chunk_while(&:==).map(&:join) # or .map(&:length)
#⇒ ["aa", "b", "aaa"]

紅寶石> = 2.3 (歸Cary Swoveland所有)

'aabaaa'.each_char.chunk(&:itself).map(&:join)

∀紅寶石

'aabaaa'.scan(/(\w)(\1*)/).map(&:join)
#⇒ ["aa", "b", "aaa"]

'aabaaa'.scan(/(\w)(\1*)/).map(&:join).map(&:length)
#⇒ [2, 1, 3]

您可以將String.prototype.match()RegExp /(\\w)(?=\\1|[^\\1])\\1+|(\\w)(?!\\2)/g)配合使用以匹配單詞字符然后是一個或多個捕獲組或單詞,然后是捕獲組。

或者,如@mudasobwa所建議,使用RegExp /(\\w)(\\1*)/g

要獲得每個匹配組的.length ,您可以創建一個數組,迭代匹配數組,將屬性設置為match的第一個元素或匹配組本身的對象推送。 或利用Array.prototype.map()返回每個匹配組的.length

"aabaaa".match(/(\w)(?=\1)\1+|(\w)(?!\2)/g)

 let str = "aabaaa"; let groups = str.match(/(\\w)(?=\\1)\\1+|(\\w)(?!\\2)/g); let matches = []; for (let match of groups) { matches.push({[match]: match.length}); } let len = groups.map(({length}) => length); console.log(groups, matches, len); 

在Ruby中

'aabaaa'.scan(/(?<s>(?<c>.)\k<c>*)/).map(&:first)
# => ["aa", "b", "aaa"]

'aabaaa'.scan(/(?<s>(?<c>.)\k<c>*)/).map{|s, _| s.length}
# => [2, 1, 3]

暫無
暫無

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

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