How to match regex in this case

Viewed 54

I'm trying to match a regex with the following phrases:

RENT3 - LOCALIZA
HGRE11 - FII HG REAL
HGLG11 - FII CSHG LOG
HGBS11 - FII CSHGSHOP
KNRI11 - FII KINEA
NTCO3 - GRUPO NATURAON      NM
ITUB3 - ITAUUNIBANCO
ITSA4 - ITAUSA
ITSA4 - ITAUSA

I have trying using \s-\s(\w+)\w*$ and at the moment is getting some lines as you can check in this example:

https://regex101.com/r/I4JkVP/2

How can I getting all lines?

My objetive with this regex is to remove all words after the first word, for example:

RENT3 - LOCALIZA

after keeps only word: "RENT3".

4 Answers

Instead just capture the first word as a group:

(?<identifier>\w+).*

Then for each line call match and if it matches, then:

String identifier = matcher.group(“identifier”)

Much easier to read.

To match all first words:

^\w+(?=\s+-)

Explanation

  • ^ Start of string
  • \w+ Match 1+ word chars
  • (?=\s+-) Positive lookahead, assert what is on the right is 1+ whitespace chars and -

For your example data, you can also leave out the ^

Regex demo


To remove all after the first word which is followed by a hyphen, you can use a capturing group and use that in the replacement.

^(\w+)\s*-.*

Regex demo

I replaced the last \w with . and works.

Related