pyff
pyff

Reputation: 1

More efficient way splitting than this?

Is there a more efficient way of splitting a string than this?

String input = "=example>";
String[] split = input.split("=");
String[] split1 = split[1].split(">");
String result = split1[0];

The result would be "example".

Upvotes: 0

Views: 118

Answers (9)

christopher
christopher

Reputation: 27336

String result = input.replaceAll("[=>]", "");

Very simple regex!

To learn more, go to this link: here

Upvotes: 2

Diego Urenia
Diego Urenia

Reputation: 1630

Regex would do the job perfectly, but just to add something new for future solutions you also could use a third party lib such as Guava from Google, it adds a lot of functionalities to your project and the Splitter is really helpful to solve something like you have.

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35547

You can try this too

    String input = "=example>";
    System.out.println(input.replaceAll("[^\\p{L}\\p{Nd}]", ""));

This will remove all non-words characters

Upvotes: 0

Prabhaker A
Prabhaker A

Reputation: 8473

try this

String result = input.replace("[\\W]", "")

Upvotes: 0

das_weezul
das_weezul

Reputation: 6142

You can do it more elegant with RegEx groups:

String sourceString = "=example>";
// When matching, we can "mark" a part of the matched pattern with parentheses...
String patternString = "=(.*?)>";
Pattern p = Pattern.compile(patternString);
Matcher m = p.matcher(sourceString);
m.find();
// ... and access it later
String result = m.group(1);

Upvotes: 1

Zaziki
Zaziki

Reputation: 418

You can try this regex: ".*?((?:[a-z][a-z]+))"

But it would be better when you use something like this:

String result = input.substring(1, input.length()-1);

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

If the string of yours defenitely constant format use substring otherwise go fo regex

result = result.substring(1, result.length() - 1); 

Upvotes: 1

Mike Thomsen
Mike Thomsen

Reputation: 37506

If you just want to get example out of that do this:

input.substring(1, input.lastIndexOf(">"))

Upvotes: 1

anubhava
anubhava

Reputation: 784898

Do you really need regex. You can do:

String result = input.substring(1, input.length()-1);

Otherwise if you really have a case for regex then use character class:

String result = input.replaceAll("[=>]", "");

Upvotes: 1

Related Questions