Marius Prollak
Marius Prollak

Reputation: 368

Regex - Remove all characters before and after

Is is it possible to remove all characters before (and including) every character to third ' and also everything after (and including) the fourth ', basically isolating the text inside the 3rd and 4th '

example:

a, 'something', 'ineedthistext', 'moretexthere'

should result in

ineedthistext

Upvotes: 1

Views: 3653

Answers (3)

Jerry
Jerry

Reputation: 71538

Regex might not be the best tool to do this (split by comma/apostrophe might actually be a better way), but if you want regex...

Maybe instead of removing all the characters before and after ineedthistext, you can capture ineedthistext from the group.

I would use something like:

^.*?'.*?'.*?'(.*?)'

Tested with rubular.

Upvotes: 1

John Willemse
John Willemse

Reputation: 6698

Derived from this answer, a possible solution is:

Regex.Match(yourString, @"\('[^']*)\)").Groups[2].Value

The code looks for all strings embedded between 2 single quotes, and puts them in groups. You need the 2nd group.

To alter your string directly, effectively removing the unwanted characters, you could use:

yourString = Regex.Match(yourString, @"\('[^']*)\)").Groups[2].Value

Upvotes: 0

Ben Green
Ben Green

Reputation: 4121

Try

public String stringSplit(String input) {
    String[] wordArray = input.split("'");
    String requiredText = wordArray[3];
    return requiredText;
}

This will work if you always want the bit between the 3rd and 4th '.

Upvotes: 0

Related Questions