0

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 [a-z] group)

(?=.*\|\|(\d+)\|\|)(?=.*\b([a-z]+\b))
7
  • You can't do it properly without an infinite-width lookbehind or some extra code. Is it used in C#? Commented Aug 22, 2019 at 8:59
  • Do you always have exactly 4 values in between pipes, per line? Commented Aug 22, 2019 at 8:59
  • @TimBiegeleisen - no, there can be more or less values Commented Aug 22, 2019 at 9:08
  • What language/tool are you using? Commented Aug 22, 2019 at 9:10
  • 1
    I don't know/use Ruby, but I would suggest just extracting the first value, then splitting your string on ||, and finally piecing it back together. Commented Aug 22, 2019 at 9:16

2 Answers 2

2

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('||')}||"
Sign up to request clarification or add additional context in comments.

Comments

1
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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.