AmirGh
AmirGh

Reputation: 65

Regex Matching, when there is a pattern moving backward in the target String?

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

Answers (2)

elixenide
elixenide

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 line

Upvotes: 4

Avinash Raj
Avinash Raj

Reputation: 174756

Just do splitting on the first and second space from last.

string.split("\\s+(?=\\S+\\s+\\S+$)|\\s+(?=\\S+$)");

DEMO

Upvotes: 2

Related Questions