user1531352
user1531352

Reputation:

RegEx Find and Replace Sentence

I'm looking for a way to find and replace a sentence using regex. The regex should be able to find a sentence of any length. I can get the entire sentence with .* but that doesn't allow it to replace with \1.

FIND:
"QUESTION1" = "What is the day satellite called?"
"ANSWER1" = "The sun"

REPLACE:
<key>What is the day satellite called?</key>
<key>The sun</key>

Upvotes: 0

Views: 1595

Answers (5)

tokhi
tokhi

Reputation: 21616

For those who are coming from google search, you can play with this great tool here to find the right regex expression to use: http://regexr.com/

Upvotes: 0

zx81
zx81

Reputation: 41838

Perl One-Liner

A compact approach: search for (?m)"([^"]+)"$

Replace with <key>$1</key> if you want <key>What is the day satellite called?</key>

or

Replace: "<key>$1</key>" if you want "<key>What is the day satellite called?</key>"

With a perl one-liner:

perl -pe 's!(?m)"([^"]+)"$!<key>$1</key>!g' yourfile

Upvotes: 0

Vijay
Vijay

Reputation: 67291

using perl:

> cat temp
"QUESTION1" = "What is the day satellite called?"
"ANSWER1" = "The sun"

> perl -lne 'print "<key>".$1."<\/key>" if(/\".*?\".*?\"(.*?)\"/)' temp
<key>What is the day satellite called?</key>
<key>The sun</key>
> 

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174766

You need to use capturing groups. So that you can refer the captured groups through back-reference.

Regex:

.*(?<= \")([^"]*).*

Replacement string:

<key>\1</key> 

DEMO

Upvotes: 1

hjpotter92
hjpotter92

Reputation: 80649

Find using the following expression (modifiers required: g and m):

^[^=]+= "(.*?)"$

and then replace them using:

<key>$1</key>

or

<key>\1</key>

Upvotes: 0

Related Questions