Regex for placing double quotes for particular field

I have a string like this:

String a = 'ABC(rfg) OR DEF(3dsgf56737(fg)sdg) OR KLM(dfgrg) AND DEF(ghthd)';

I want to place double quotes for DEF field alone:

String a = 'ABC(rfg) OR DEF("3dsgf56737(fg)sdg") OR KLM(dfgrg) AND DEF("ghthd")';


You can try

String b = a.replaceAll("DEF\\((\\S+)\\)", "DEF(\"$1\")");

What tools are you using to do this? sed? Python? Java?

A regex you could use with (eg) sed is:


The g means match globally, and the bit in the DEF basically searches for matched pairs of parenthesis within the outer one (the (fg) in your example), or other non-parentheses.

Of course you would tailor the regex to your particular situation -- for example, if you only ever expect there to be alphanumerics and parentheses inside the DEF, then instead of [^(] you could use [a-z0-9], etc.

@NullUserException's comment is still pertinent though - you tagged the question java and python but have not specified which tool/language you intend to use?

For example, you could use sed:

echo 'ABC(rgt) ... etc' | sed -r -e 's/DEF\((([^(]*|\([^)]*\))+)\)/DEF("\1")/g'

In any case, whether you use Java or Python, the regex I've given will be much the same.

Need Your Help

Convert all unicode characters to a specific character

c# .net sql sql-server-2005 unicode

Is there any way to tell if a character isn't an Extended-ASCII character?

Android Studio “class” or “interface” expected

java android android-studio

i am following instruction provide in to display user location. But leading to above stated compilation error.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.