Regex: First occurrence between two character if there are two characters

Viewed 140

I want to get the first occurrence between two character if both exist, otherwise get what is before the first character found.

For example, on the strings below:

25 de Março - Centro Histórico de São Paulo, São Paulo - SP, Brasil
Centro Histórico de São Paulo, São Paulo - SP, Brasil
Rua Hamilton Prado, 398 - Chácara Belenzinho, São Paulo - SP, 03376-000, Brasil

I want to get what is behind the '-' character. However, the second string only has one '-', so I want to get everything that is behind it.

The results I am looking for are:

Centro Histórico de São Paulo, São Paulo
Centro Histórico de São Paulo, São Paulo
Chácara Belenzinho, São Paulo

I tried the following regex [^-\n]+(?=-[^\n-]*$) but it does not return what I want on the last string.

Is it possible to solve with regex?

2 Answers

You could optionally match the first part, and capture the second part in a group

^(?:.+?- )?(.+?) -
  • ^ Start of string
  • (?:.+?- )? Optionally match as least as possible chars until -
  • ( Capture group 1
    • .+? Match as least as possible chars
  • ) - Close group and match -

Regex demo

Or for example with the surrounding spaces and a negated character class matching any char except a newline or -

^(?:[^\n-]+-)?([^\n-]+)-

Regex demo

IMHO it would be better to loop through the string by yourself.

const str = `25 de Março - Centro Histórico de São Paulo, São Paulo - SP, Brasil
Centro Histórico de São Paulo, São Paulo - SP, Brasil
Rua Hamilton Prado, 398 - Chácara Belenzinho, São Paulo - SP, 03376-000, Brasil`;

const addresses = str
.split('\n')
.map(address => address
    .split(' - ')
    .slice(-2, -1)
).join('\n');

console.log(addresses);

The logic is to take the second last part of each address.

Related