Using regex to capture text between "^1234:" and ", ^5678:"

37 Views Asked by At

I'm trying to create a regex query to extract everything between the characters

^1234: 

and

, ^5678:

I tried the following and it doesn't work. Am i on the right track?

^(\^1234),(\^5678)$

Example text:

54:16812344266, ^1234:iwantthistext, ^5678:idontwantthis, ^0000: idontwantthiseither
2

There are 2 best solutions below

0
Foo L On

If you're using sed, you can do something like this:

$ echo '54:16812344266, ^1234:iwantthistext, ^5678:idontwantthis, ^0000: idontwantthiseither' | sed 's/.*\^1234:\(.*\), \^5678.*/\1/'
iwantthistext

You want to use the () to capture the match in between the strings. Then replace the full value with the capture text.

The first .* will match everything before ^1234 and the second .* will match everything after ^5678. The ^ needs escaping with a backslash so sed doesn't use it for interpolation.

0
unalignedmemoryaccess On

Like this: \^1234(.*?), \^5678

With input 54:16812344266, ^1234:iwantthistext, ^5678:idontwantthis, ^0000: idontwantthiseithere will output:

https://regex101.com/r/22Fplx/1