Catalin
Catalin

Reputation: 147

Regex match only first char

So basicly I have these lines:

line1:blabla:etcetc
line2:blabla2:etcetc2
line3:blabla3:etcetc3

I need to capture only the first ' : ' . This is my regex now,but it captures all the ' : '

[(:*?)]

Upvotes: 4

Views: 17386

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626699

Note that [(:*?)] regex matches 1 symbol that is either a (, or :, *, ?, or ) since the outer brackets form a character class (or a bracket expression in POSIX regex) where you define characters, or their ranges, that this construct can match, but it will match 1 char that belongs to the set/ranges.

The first : can be matched with

^([^:]*):

And replace with $1\t.

See the regex demo

Details:

  • ^ - start of string
  • ([^:]*) - Group 1 capturing 0+ chars other than : with a nregated character class [^:] (note we capture what we need to keep)
  • : - a literal : (note we match what we need to replace)

And the $1 in the replacement pattern refers to the value captured in Group 1.

Upvotes: 4

Related Questions