2

I have a string variable Result that contains a string like:

"<field1>text</field1><field2>text</field2> etc.."

I use this code to try to split it:

Result = Result.replace("><", ">|<");

String[] Fields = Result.split("|");

According to the many websites, including this one, this should give me an array like this:

Fields[0] = "<field1>text</field2>"
Fields[1] = "<field2>test</field2>"
etc...

But it gives me an array like:

Fields(0) = ""
Fields(1) = "<"
Fields(2) = "f"
Fields(3) = "i"
Fields(4) = "e"
etc..

So, what am I doing wrong?

0

2 Answers 2

2

Your call to split("|") is parsing | as a regular-expression-or, which on its own will split between every character.

You can regex-escape the character to prevent this from occurring, or use a different temporary split character altogether.

String[] fields = result.split("\\|");

or

result = result.replace("><", ">~<");
String[] fields = result.split("~");
Sign up to request clarification or add additional context in comments.

Comments

2

Try doing

String[] fields = result.split("\\|");

Note that I've used more conventional variable names (they shouldn't start with capital letters).

Remember that the split methods takes a regular expression as an argument, and | has a specific meaning in the world of regular expressions, which is why you're not receiving what you were expecting.


Relevant documentation:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.