I am working on a project and currently I'm stuck.
I'm trying to parse from a string that's in this format
<string> <integer> <integer> <integer> <string>
The string is given by the user, for example this is users input:
Foo Bar 15 0 0 The quick brown fox jumps over the lazy dog
How would I get something like this?
['Foo Bar', 15, 0, 0, "The quick brown fox jumps over the lazy dog"]
Note: Strings can include integers
Thanks.
Regex seems like a reasonable solution, but you can do it with one call to .split
.
When you include a capturing group ( (...)
) in the regex that you pass to .split
, the captured text is included in the result array. This means you can split the text around the numbers but also capture the numbers with a pattern like /\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+/
.
For example:
var input = "Foo Bar 15 0 0 The quick brown fox jumps over the lazy dog" var regex = /\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+/; var result = input.split(regex); console.log(result);
I'd personally use RegEx. Is the format of the string always the same?
If so.... I'd match the integer values:
"Foo Bar 15 0 0 The quick brown fox jumps over the lazy dog".match(/(\\d+\\s)+/g)
Then I would split using the resulting match.
let numbers = "Foo Bar 15 0 0 The quick brown fox jumps over the lazy dog".match(/(\d+\s)+/g)
["15 0 0 "]
let words = "Foo Bar 15 0 0 The quick brown fox jumps over the lazy dog".split(numbers[0].trim())
(2) ["Foo Bar ", " The quick brown fox jumps over the lazy dog"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.