Regular Expression to get what’s outside of brackets

Asked

Viewed 824 times

3

Sample text:

Itaú [123.456,89]

To get what’s inside the brackets (including the brackets) I used:

\[(.*?)\]

The question is how to get what is outside?

I imagine it’s a denied list, something simple. I’ve searched over time and nothing.

If possible, I also wanted to know how to get what is inside the bracket, without including the brackets?

All in one expression, without prolonging the code [pedaling].

Example text can be:

"Itaú 1 [123.456,89]", "Itaú 2 [543.456,59]", "Banco do Brasil [987.543,21]", etc.

That is, include accents, more than one word, so it has spaces and can occur starting with numbers.

  • Is there another example? the lines always start with a-Z0-9 followed by conchetes?

  • Example text can be "Itaú 1 [123.456,89]", "Itaú 2 [543.456,59]", "Banco do Brasil [987.543,21]", etc. That is, include accents, more than one word, so it has spaces and can occur to start with numbers.

4 answers

3

My suggestion is to use denied classes to match "everything that is not bracket": [^\[]+ and [^\]]+.

Gathering and placing the groups was: ([^\[]+) (\[([^\]]+)\])

Example:

var str = 'Itaú 1 [123.456,89]';
var result = str.replace(/([^\[]+) (\[([^\]]+)\])/, 'grupo 1: "$1"<br>grupo 2: "$2"<br>grupo 3: "$3"<br>');
document.body.innerHTML = result;

2


See working on Regex.

Any clarification ask.

Pattern:

/^([^\]]+) \[([^\]]*)\]/gm

Input:

Itau [2.265,41]
Bradesco [1.375,21]
Santander Bradesco [784,12]
Caixa 2 []

Match:

MATCH 1
1.  [0-4]   `Itau`
2.  [6-14]  `2.265,41`
MATCH 2
1.  [16-24] `Bradesco`
2.  [26-34] `1.375,21`
MATCH 3
1.  [36-54] `Santander Bradesco`
2.  [56-62] `784,12`
MATCH 4
1.  [64-71] `Caixa 2`
2.  [73-73] ``

1

In javascript, I would do as follows:

To get only the word Itaú:

'Itaú [123.456,89]'.replace(/(\[.*\])/g, '');

To get what is inside the brackets (without the brackets):

'Itaú [123.456,89]'.match(/\[(.*)\]/)[1]
  • I’m not very good at regexp :(

  • Example text can be "Itaú 1 [123.456,89]", "Itaú 2 [543.456,59]", "Banco do Brasil [987.543,21]", etc. That is, include accents, more than one word, so it has spaces and can occur to start with numbers.

  • I think the magic of regular expressions is fantastic, but I also have a hard time finding Pattern. Due to the delay, the "ride" often appears to arrive at the solution with more lines, hehe.

0

See working on Regex.

https://regex101.com/r/vD2kN9/1

$re = "/([A-Za-zÀ-ú0-9]+)([.,]?)/"; 
$str = "Itaú [123.456,89]"; 

preg_match_all($re, $str, $matches);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.