SRS
SRS

Reputation: 449

How to remove the contents of a string after the first occurrence of a character in java?

I have a set of strings with each string containing letters, numbers & symbols. I would like to extract the contents of a string until the occurrence of a number & preceding symbol. Here is an example:

Axis-1.4.5
Limo_9.5.6R
Dent-ist-0C.4E
Log4M-1.2.0
Hello-World-1.0

These are my strings. What I want from this as my output is:

Axis
Limo
Dent-ist
Log4M
Hello-World

I used the patterns replaceAll("\d","") & replaceAll("[-+.^:,_]","") to remove the numbers and the symbols. But what I got as my outpus with this is:

Axis
LimoR
DentistCE
LogM
HelloWorld

Could someone please let me know how to trim the string properly for this scenario?

Upvotes: 0

Views: 537

Answers (1)

user94559
user94559

Reputation: 60153

I think replaceFirst("[-+.^:,_]\d.*", "") should do what you want.

You can read that as "a 'symbol' followed by a digit followed by everything else in the string."

Upvotes: 2

Related Questions