6

How would you parse the values in a string, such as the one below?

12:40:11  8    5                  87

The gap between numbers varies, and the first value is a time. The following regular expression does not separate the time component:

str.split("\\w.([:]).")

Any suggestions?

3
  • Is the file fixed-width delimited? Commented Jun 22, 2010 at 1:21
  • 1
    If you can explain why you think "\\w.([:])." would work, I can elaborate on where the logic went wrong. Right now I'm not even sure how you came to that. Commented Jun 22, 2010 at 1:32
  • what is the expected output? [12,40,11,8,5,87] ? Commented Jun 22, 2010 at 1:33

2 Answers 2

9

The regex \s+ matches one or more whitespaces, so it will split into 4 values:

"12:40:11", "8", "5", "87"

As a Java string literal, this pattern is "\\s+".

If you want to get all 6 numbers, then you also want to split on :, so the pattern is \s+|:. As a Java string literal this is "\\s+|:".

References


On Scanner

Instead of using String.split, you can also use java.util.Scanner, and useDelimiter the same as what you'd use to split. The advantage is that it has int nextInt() that you can use to extract the numbers as int (if that's indeed what you're interested in).

Related questions

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this is correct, "\\s+" works for me. Thank you very much!
2

See the Pattern doc and String API.

Using

str.split("\\s+");

will yield

[ '12:40:11', '8', '5', '87' ]

or

str.split("\\s+|:");

should yield

[ '12', '40', '11', '8', '5', '87' ]

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.