views:

40

answers:

3

Hello all,

I'm not sure if this is a regex question, but i need to be able to grab whats inside single qoutes, and surround them with something. For example:

this is a 'test' of 'something' and 'I' 'really' want 'to' 'solve this'

would turn into

this is a ('test') of ('something') and ('I') ('really') want ('to') ('solve this')

Any help you could provide would be great!

Thanks!

A: 

If you can ignore single apostrophes, you could do like this (C# code, should be easy to translate)

string input = "this is a 'test' of 'something' and ...";
Console.WriteLine(Regex.Replace(input, "'([^']*)'", "('$1')"));
Rubens Farias
lol, posting C# is that bad? This code can't help OP to find a way to solve his problem?
Rubens Farias
+1  A: 
String str = "this is a 'test' of 'something'";
String rep = str.replaceAll("'[^']*'", "($0)"); // stand back, I know regex

What I did here is use toe replaceAll() method which searches for all matches for regex "'[^']*'" and replaces them with regex "($0)".

The pattern "'[^']*'" matches all substrings that start and end with a single quote ('), and between them are any characters, except another single quote ([^']), and those can appear any number of times (*). Replacing those with "($0)" means taking every match ($0) and wrapping it with parenthesis.

Yuval A
Do you mind including a couple of lines explaining it? Thanks ;]
ApacheImageUser
@ApacheImageUser - No problem.
Yuval A
A: 

One easy way (but not always valid) is the following If always you have [ '] and [' ] , you can do this:

myString.replace(" '"," ('"); // replaces all <space_apostrophe> with <space_bracket_apostrophe>

Do the same for the rear bracket :)


One more thing - why do you even have apostrophes-surrounded words? Is it a must that they must be like that? If you made them like that, why did you do it and then look for another approach !

Leni Kirilov