简体   繁体   中英

Regex - capture multiple groups and combine them multiple times in one string

I need to combine some text using regex, but I'm having a bit of trouble when trying to capture and substitute my string. For example - I need to capture digits from the start, and add them in a substitution to every section closed between ||

I have:

||10||a||ab||abc||

I want:

||10||a10||ab10||abc10||

So I need '10' in capture group 1 and 'a|ab|abc' in capture group 2

I've tried something like this, but it doesn't work for me (captures only one [az] group)

(?=.*\|\|(\d+)\|\|)(?=.*\b([a-z]+\b))

I would achieve this without a complex regular expression. For example, you could do this:

input = "||10||a||ab||abc||"
parts = input.scan(/\w+/)   # => ["10", "a", "ab", "abc"]
parts[1..-1].each { |part| part << parts[0] }   # => ["a10", "ab10", "abc10"]

"||#{parts.join('||')}||"
str = "||10||a||ab||abc||"

first = nil
str.gsub(/(?<=\|\|)[^\|]+/) { |s| first.nil? ? (first = s) : s + first }
  #=> "||10||a10||ab10||abc10||" 

The regular expression reads, "match one or more characters in a pipe immediately following two pipes" ( (?<=\\|\\|) being a positive lookbehind ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM