neenkart
neenkart

Reputation: 156

Regex to get all data before second last special character

I couldnt find any previously asked question similar to this. I need a regex to get all the data before second last special character.

For example:

suite 1, street 1, zip city, country

I need only suite 1, street 1.

I know how to get the data before just the last special character using [^,]*$ but not the second last one.

Upvotes: 2

Views: 1205

Answers (4)

The Scientific Method
The Scientific Method

Reputation: 2436

you can use look ahead

.+(?=.*,.*,)

explanation

  • .+ matches everything until the position look head starts , if the look ahead does not fail
  • Positive Look ahead (?=.*,.*,) asserts two commas exist at the end

check demo

Upvotes: 1

Nambi_0915
Nambi_0915

Reputation: 1091

Try (([ \w]+,?){2})(?=,) and dont use global flag (doesn't return after first match)

regex

Upvotes: 0

blhsing
blhsing

Reputation: 107095

You can use the following regex and the first capturing group will have your desired substring:

(.*)(?:,[^,]*){2}$

Demo: https://regex101.com/r/AWpsL3/1

Or if the tool you're using does support capturing groups, you can use the following regex with lookahead instead:

.*(?=(?:,[^,]*){2}$)

Demo: https://regex101.com/r/AWpsL3/4

Upvotes: 5

MaddawgX9
MaddawgX9

Reputation: 151

Depending on the implementation of regex, it may not support lookaround (which is what the above solution uses). A work around for this would be to perform a string split on your delimiter character (in this case, comma). Then perform a string join of the first two elements.

mystr = 'suite 1, street 1, zip city, country';
parts = mystr.split(',');
return parts[0]+','+parts[1];

Upvotes: 0

Related Questions