AabinGunz
AabinGunz

Reputation: 12347

Matching only 1st occurence of any character

I want to know how to match just the 1st character occurrence using regex

Output

    # Address 
cleanse.library.addressDoctor.AddressDoctor.UnlockCode:YR\\FKNT5ST3WCM:\\1J4JTCQQMH/H
cleanse.library.addressDoctor.AddressDoctor.DatabasePath:C:/AddressDoctor
cleanse.library.addressDoctor.AddressDoctor.Optimization:ADDRESSES_SORTED_BY_COUNTRIES
cleanse.library.addressDoctor.AddressDoctor.MemoryMB:600
cleanse.library.addressDoctor.AddressDoctor.CorrectionType:CORRECT_ONLY
cleanse.library.addressDoctor.AddressDoctor.PreLoad.CERTIFIED.PRELOAD_PART:US
cleanse.library.addressDoctor.AddressDoctor.PreLoad.CERTIFIED.PRELOAD_FULL:
cleanse.library.addressDoctor.AddressDoctor.PreLoad.CORRECTION_ONLY.PRELOAD_PART:CA, US
cleanse.library.addressDoctor.AddressDoctor.PreLoad.CORRECTION_ONLY.PRELOAD_FULL:

In this case I want to match just : (the 1st occurrence)

Update

Note: : (1st occurrence in every line)

You can test here

Upvotes: 1

Views: 119

Answers (3)

stema
stema

Reputation: 93056

Are you applying your regex separately on each row?

If yes, then just don't use the greedy modifier. (See on Regexr)

How you use it depends on your language, but I assume every language will have the possibility to match non greedy, i.e. stop matching after the first match.

Edit:

What about using capturing groups?

^([^:\r\n]*):(.*)$

See it here on Regxr

You will find the part before the first : in group 1 and the part behind till the end of the row in group 2.

Upvotes: 0

Bart Kiers
Bart Kiers

Reputation: 170308

The pattern:

^[^:]*:

matches the start of the input (^), followed by zero or more characters other than : ([^:]*) followed by a :.

So, this matches the first : (and of course everything that precedes the :).

So, let's say you would like to replace the first : with an @. You then simply group everything that precedes the first :, like this:

^([^:]*):

and replace it with:

$1@

As shown here: http://regexr.com?2v8h8

EDIT

Most regex implementations do not allow a pattern to match the first : in a line. You'd need a variable width look-behind assertion for such a thing, which simply is not supported by most languages.

You could read the file line by line and split on the : and provide a 2nd parameter that indicates the size of the array being returned:

array = line.split(/:/, 2)

Many regex implementation have such a method (I can't be more specific since I don't know the language you're using).

Upvotes: 3

Toto
Toto

Reputation: 91518

Why don't just use :

/:/

This will match the first column :

Upvotes: 0

Related Questions