yvgwxgtyowvaiqndwo
yvgwxgtyowvaiqndwo

Reputation: 477

Regex for not starting with specific word

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

Upvotes: 3

Views: 950

Answers (2)

The fourth bird
The fourth bird

Reputation: 163207

The pattern that you tried ^(?![^:]+:) means: assert that to the right of the current position there are not 1 or more characters other than : and then match :

You get no right replacement for the strings like 1 : A because the negated character class [^:] also matches a whitespace char.

You can exclude matching whitespace characters as well:

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

See the replacements at the regex101 demo.

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626709

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.

Upvotes: 2

Related Questions