Home > OS >  Regex for not starting with specific word
Regex for not starting with specific word

Time:05-05

i try to add before every word that do not have a starting [string]: to have Line: at its start so i did this regex ^(?![^:] :) https://regex101.com/r/oMF8ks/1

and if i write

1
2
3

it returns what i want expected

Line:1
Line:2
Line:3

and for

Line:1
Line:2
Line:3

it returns same as wanted

but my problem when i try to apply it on https://regex101.com/r/K0z3bc/1

1 : A
2 : B
3 : C

i expected

Line:1 : A
Line:2 : B
Line:3 : C

but i only got

1 : A
2 : B
3 : C

but when i change the regex to ^(?!Line:) https://regex101.com/r/49i9tQ/1 then it works but i want it to work for all words and not just Line

CodePudding user response:

You can use

^([^:\s]  )(?!:)

and replace with Line:$1.

See the regex demo. Details:

  • ^ - start of string
  • ([^:\s] ) - Group 1: one or more chars other than : and whitespace (possessive quantifier prevents backtracking into the [^:\s] pattern and thus prevents partial matching if a colon is present further in the string)
  • (?!:) - not immediately followed with a colon.

You may also omit the group and then use ^[^:\s] (?!:) and replace with Line:$0. See this regex demo.

  • Related