How to split a string without losing any char in java -


I am using Eclipse for Java.

I want to split the input line from the user without losing, there is an input line for any four example: +2+ sqrt (25) -41 * 3-ABS (-4) -62 / 2

and output should be: + 2, + sqrt (25), - 41, * 3, -bs (-4), -62, / 2

(If I "+" or etc. "+" itself will be removed.)

What should I do?

My code is something like this:

  scanner scanner = new scanner (System.in); String str = scanner NXtine (); String [] parts; Parts = str.split ("!!!! !!?"); // I do not know what to put here  

You can do it regularly Expression in Java assumes that you can not have nested parenthias (this is a strict requirement)

  list & lt; String & gt; Parts = new arreelist & lt; String & gt; (); String input = "+2 + sqrt (25) -41 * 3-stomach (-4) -62 / 2"; Pattern p = Pattern.compile ("[\\ + \\ - / \\ *] [^ \\ + \\ - \\ * / \\ () + (\\ ([^ \ \ (\\)] * \\)) "); Matcher m = p.matcher (input); While (m.find ()) {parts.add (m.group ());}  

If you want an array you want:

 < Code> parts.toArray (new string [parts.size ()]);  

This will give you a simple array of strings. I am using Java collections to handle array creation because there is no way to know the size of the array before parse string.

Explanation about this regax: [\\ + \\ - / \\ *] appears for operator mark [^ \\ + \\ - \\ * / \\ () + operator searches everything except the left and left brackets (\\ ([^ \\ (\\)] * \\))? Search for a bracket content without nested brackets

This code returns:

  +2 + sqrt (25) -41 * 3 - stomach (- 4) -62 / 2  

If you need nested brackets, then you have to implement a parser, and I'll give it to you Google.


Comments

Popular posts from this blog

c# - SignalR: "Protocol error: Unknown transport." when navigating to hub -

class - Kivy: how to instantiate a dynamic classes in python -

python - mayavi mapping a discrete colorbar on a surface -