regex: if a line doesn't start with a particular string, add it as prefix
Asked Answered
N

4

6

I've this text:

£££££Ciao a tutti§§§§§,§§§§§2009§§§§§,§§§§§8§§§§§
£££££Il mio nome è Geltry§§§§§,§§§§§2009§§§§§,§§§§§6§§§§§
Bla bla bla§§§§§,§§§§§2010§§§§§,§§§§§7§§§§§
£££££Le amiche della sposa§§§§§,§§§§§2011§§§§§,§§§§§3§§§§§

With TextCrawler I find all the lines that have not £££££ as a prefix, so:

^((?!£££££).)*$

What I should write as replacement?

Reg Ex: ^((?!£££££).)*$
Replacement: ?  <-- what write here?

to have:

£££££Ciao a tutti§§§§§,§§§§§2009§§§§§,§§§§§8§§§§§
£££££Il mio nome è Geltry§§§§§,§§§§§2009§§§§§,§§§§§6§§§§§
£££££Bla bla bla§§§§§,§§§§§2010§§§§§,§§§§§7§§§§§
£££££Le amiche della sposa§§§§§,§§§§§2011§§§§§,§§§§§3§§§§§
N answered 11/8, 2012 at 9:42 Comment(1)
Which language? The semantics are not 100% universal. You might want to try inputString.replace(/(^£{5})/,'£££££');Laryngitis
G
19

Search:

^(?!£££££)(.+)$

Replace:

£££££$1

First, your regex was incorrect. ^((?!£££££).)*$ matches a line that doesn't contain £££££ anywhere. It also captures only the last character of the line, where you want it to capture the whole line.

My regex matches only lines that don't start with £££££. It captures the whole line in group number one, and (according to the manual), the $1 in the replacement string reinserts the captured text.

I also changed the * to + so it won't match empty lines and replace them with £££££.

Gunn answered 11/8, 2012 at 10:54 Comment(1)
PAY ATTENTION: in TextCrawler, set MULTILINE ANCHOR to 'ON'N
K
4

You don't need to capture anything, just insert if the line doesn't start with £££££:

Search: ^(?!£££££)

Replace: £££££

If you're not matching one line at a time, you also need to ensure that it's a multiline search.

Kisor answered 11/8, 2012 at 19:47 Comment(1)
Right, but Alan Moore solution won't keep empty lines. It know that it was not a specification in my question, but his suggestion is right what I need :-) +1 4UN
S
1

You can use () to match subexpression:

( subexpression )
Captures the matched subexpression and assigns it a zero-based ordinal number.

(? subexpression)
Captures the matched subexpression into a named group.

so your Regex can be like:

(^(?:(?!£££££).)*$)
//or
(?<line>^(?:(?!£££££).)*$)

and for replacement:

$ number
Substitutes the substring matched by group number.

${ name }
Substitutes the substring matched by the named group name.

your replacement can be like this:

£££££$1
//or
£££££${line}
Sanalda answered 11/8, 2012 at 9:50 Comment(0)
P
-1

Using this regexp: ^(((?!£££££).)*)$

Write this as replacement: £££££^(\1)$

\1 will be the source match, that in your case it is the whole row.

Puncture answered 11/8, 2012 at 9:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.