Reputation: 156
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
Reputation: 2436
you can use look ahead
.+(?=.*,.*,)
explanation
.+
matches everything until the position look head starts , if the look ahead does not fail(?=.*,.*,)
asserts two commas exist at the endUpvotes: 1
Reputation: 1091
Try (([ \w]+,?){2})(?=,)
and dont use global flag (doesn't return after first match)
Upvotes: 0
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
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