Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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§§§§§
like image 879
Geltrude Avatar asked Aug 11 '12 09:08

Geltrude


People also ask

What does ?= * Mean in RegEx?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).

What does \b represent in RegEx?

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a “word boundary”.

What does RegEx 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.


2 Answers

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 £££££.

like image 194
Alan Moore Avatar answered Sep 28 '22 07:09

Alan Moore


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.

like image 39
MRAB Avatar answered Sep 28 '22 06:09

MRAB