Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse values from a string

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?

like image 295
jgg Avatar asked Jun 22 '10 01:06

jgg


People also ask

How do you parse a string?

String parsing in java can be done by using a wrapper class. Using the Split method, a String can be converted to an array by passing the delimiter to the split method. The split method is one of the methods of the wrapper class. String parsing can also be done through StringTokenizer.

How do you parse a value?

The PARSE VALUE … WITH instruction parses a specified expression, such as a literal string, into one or more variable names that follow the WITH subkeyword. If the literal string contains character information, it is not changed to uppercase.

How do you parse a string in Python?

Use str. Call str. split(sep) to parse the string str by the delimeter sep into a list of strings. Call str. split(sep, maxsplit) and state the maxsplit parameter to specify the maximum number of splits to perform.


1 Answers

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

  • regular-expressions.info/Alternation with the Vertical Bar, Character Class, and Repetition

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

  • Validating input using java.util.Scanner
like image 64
polygenelubricants Avatar answered Sep 25 '22 01:09

polygenelubricants