Reputation: 65
I have a file with each line having the following pattern:
A<space>B<space>C
where:
What regex pattern can I use to split the line in 3?!
I currently use something like: substring(*line*.lastIndexOf(" "))
to get C, changing line to hold A B and repeat to get B, and then whatever is left is A.
But is there a way to do it with Regex?! In general how can Regex be used when the pattern is know moving backward in a string?!
Upvotes: 0
Views: 725
Reputation: 44841
This regex will do it:
^(.+?) (\S+) (\S+)$
Here's a demo. In your example, it captures three groups:
Hi I'm block A
I'mB
I'mC
Explanation:
^
start of the string(.+?)
capture any characters, but "non-greedy" (stop as soon as possible)
a space(\S+)
capture any group of non-whitespace characters
a space(\S+)
again, capture any group of non-whitespace characters$
end of the lineUpvotes: 4
Reputation: 174756
Just do splitting on the first
and second space from last
.
string.split("\\s+(?=\\S+\\s+\\S+$)|\\s+(?=\\S+$)");
Upvotes: 2