473,782 Members | 2,542 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using a regular expression to retrieve the text between two parentheses

Hi,

Supposing I had a string made up of a person's name followed by their
profession in parentheses e.g.

string strText = "Tiger Woods (golfer)";

and I wanted to extract the portion of the string between the parentheses
i.e. "golfer"

Would a regular expression be the most efficient way of doing this...?

I'm trying to do something like this:

string strProfession = String.Empty;
Regex objRegEx = new Regex("(((.|\n) *?))", RegexOptions.Ig noreCase);
foreach (Match objMatch in objRegEx.Matche s(strText)
{
strProfession = objMatch.ToStri ng();
}

but that is returning an empty string, no doubt because I haven't defined
the regular expression correctly.

Also, is it even necessary to have a foreach loop here, as in this
particular scenario there can only ever be one match...?

Any assistance gratefully received.

Mark
Jan 15 '07 #1
16 9373
Mark Rae wrote:
Supposing I had a string made up of a person's name followed by their
profession in parentheses e.g.

string strText = "Tiger Woods (golfer)";

and I wanted to extract the portion of the string between the parentheses
i.e. "golfer"

Would a regular expression be the most efficient way of doing this...?

I'm trying to do something like this:

string strProfession = String.Empty;
Regex objRegEx = new Regex("(((.|\n) *?))", RegexOptions.Ig noreCase);
foreach (Match objMatch in objRegEx.Matche s(strText)
{
strProfession = objMatch.ToStri ng();
}

but that is returning an empty string, no doubt because I haven't defined
the regular expression correctly.

Also, is it even necessary to have a foreach loop here, as in this
particular scenario there can only ever be one match...?
string s = "Tiger Woods (golfer)";
Regex re = new Regex(@"(\()([^\)]*)(\))");
string prof = re.Match(s).Gro ups[2].Value;

seems to work.

No regex will typical not be the most efficient way of coding it,
but it is simple code with a well documented syntax.

Some spagetti with IndexOf will be faster, but it would
also be much easier to introduce bugs if modifying the code.

Arne
Jan 15 '07 #2
Arne Vajhøj wrote:
Supposing I had a string made up of a person's name followed by their
profession in parentheses e.g.

string strText = "Tiger Woods (golfer)";

and I wanted to extract the portion of the string between the parentheses
i.e. "golfer"

Would a regular expression be the most efficient way of doing this...?
Regex re = new Regex(@"(\()([^\)]*)(\))");
@"\( ([^\)]+) \)", RegexOptions.Ig norePatternWhit espace

is probably a bit simpler and faster - there's no real need to capture
the parens.
No regex will typical not be the most efficient way of coding it,
but it is simple code with a well documented syntax.
You might be surprised. I compared a regex to find all tokens between
% signs (@"% (\w+) %") with a hand-coded state machine. Not only did
the hand-coded version take about 180 times as long to write (ie,
fifteen minutes vs five seconds) it also ran slower. As soon as the
task gets at all complex, a regex can save both programmer time and
run time.
Some spagetti with IndexOf will be faster, but it would
also be much easier to introduce bugs if modifying the code.
Yes, and the regex is easier to read and maintain - part of one line,
instead of three statements and some comments.

--

..NET 2.0 for Delphi Programmers
www.midnightbeach.com/.net
Jan 15 '07 #3
Hi,
string strText = "Tiger Woods (golfer)";
Others have supplied working regexes - so I won't repeat.

But perhaps you should be made aware of the limitations implicit in
regexes - the main one being commonly rendered as "regexes can't count". As
long as you are not having to deal with recursive structures, nested
delimiters and so on, regexes will often work well. But they can't be used
to "find the balancing brace", verify correct nesting or suchlike.

In theory, you can explicitly construct a regex to cope with a given maximum
number of pairs of balancing delimiters, but even to cope with a single
extra level of nestiing requires a regex pattern so complex that it's
clearer and simpler to just code the match algorithm explicitly.

And of course there is the school of thought that regexes are only rarely
the best
solution. -

"Some people, when confronted with a problem, think 'I know, I'll use
regular expressions.' Now they have two problems." - Jamie Zawinski{*1]

cheers,

gary

http://www.oxide.net.au

*[1] - For an entertaining discussion of the origins of this quote, see
Jeffrey Friedl's blog at
http://regex.info/blog/2006-09-15/247

Jan 15 '07 #4
"Arne Vajhøj" <ar**@vajhoej.d kwrote in message
news:45******** *************** @news.sunsite.d k...
string s = "Tiger Woods (golfer)";
Regex re = new Regex(@"(\()([^\)]*)(\))");
string prof = re.Match(s).Gro ups[2].Value;

seems to work.
Yes indeed - thanks very much.
No regex will typical not be the most efficient way of coding it,
but it is simple code with a well documented syntax.
OK.
Some spagetti with IndexOf will be faster, but it would
also be much easier to introduce bugs if modifying the code.
I guess so...
Jan 15 '07 #5
"Jon Shemitz" <jo*@midnightbe ach.comwrote in message
news:45******** *******@midnigh tbeach.com...
> Regex re = new Regex(@"(\()([^\)]*)(\))");

@"\( ([^\)]+) \)", RegexOptions.Ig norePatternWhit espace

is probably a bit simpler and faster - there's no real need to capture
the parens.
That returns an empty string...
>No regex will typical not be the most efficient way of coding it,
but it is simple code with a well documented syntax.

You might be surprised. I compared a regex to find all tokens between
% signs (@"% (\w+) %") with a hand-coded state machine. Not only did
the hand-coded version take about 180 times as long to write (ie,
fifteen minutes vs five seconds) it also ran slower. As soon as the
task gets at all complex, a regex can save both programmer time and
run time.
I have a real "blind-spot" with regular expressions... After over 20 years
of programming in all sorts of languages, I *still* can't do them in my
head, or look at them and know intuitively what they're doing... :-)
Jan 15 '07 #6
"Gary Stephenson" <ga**@oxide.net .auwrote in message
news:ua******** ******@TK2MSFTN GP04.phx.gbl...
Others have supplied working regexes - so I won't repeat.
OK - thanks...
Jan 15 '07 #7
Mark Rae wrote:
I have a real "blind-spot" with regular expressions... After over 20 years
of programming in all sorts of languages, I *still* can't do them in my
head, or look at them and know intuitively what they're doing... :-)
The syntax is horrible.

But it is well documented. And there are a ton of supporting
tools out there.

Arne
Jan 15 '07 #8
"Arne Vajhøj" <ar**@vajhoej.d kwrote in message
news:45******** *************** @news.sunsite.d k...
>I have a real "blind-spot" with regular expressions... After over 20
years of programming in all sorts of languages, I *still* can't do them
in my head, or look at them and know intuitively what they're doing...
:-)

The syntax is horrible.
That's for sure!
But it is well documented. And there are a ton of supporting
tools out there.
Can you recommend one? I've looked at several over the years, but almost all
of them seem to be designed to show the effect of a regular expression on a
string, rather than "build me a regular expression which will..."

If you could have found one which would have built me the "find all the text
between the opening and closing parentheses" expression, I wouldn't have
troubled the newsgroup...
Jan 15 '07 #9
Mark Rae wrote:
"Arne Vajhøj" <ar**@vajhoej.d kwrote in message
>But it is well documented. And there are a ton of supporting
tools out there.

Can you recommend one? I've looked at several over the years, but almost all
of them seem to be designed to show the effect of a regular expression on a
string, rather than "build me a regular expression which will..."

If you could have found one which would have built me the "find all the text
between the opening and closing parentheses" expression, I wouldn't have
troubled the newsgroup...
I am not aware of any english to regex translator, but an
interactive one that shows what you get out of an regex
expression is useful as well. Because it helps you
build up the regex incrementally.

Arne
Jan 15 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

28
20345
by: Daniel | last post by:
Hello =) I have an object which contains a method that should execute every x ms. I can use setInterval inside the object construct like this - self.setInterval('ObjectName.methodName()', this.pinginterval); - but is there no way to do this without using the literal ObjectName? If I write 'this.methodName()' I get "Line 1 Char 1: Object doesn't support this property or method." in IE, and nothing happens in Firebird.
10
1620
by: Harlin Seritt | last post by:
I have been looking at the Python re module and have been trying to make sense of a simple function that I'd like to do. However, no amount of reading or googling has helped me with this. Forgive my stone-headedness. I have done this with .NET and Java in the past but damn if I can't get it done with Python for some reason. As such I am sure it is something even simpler. I am trying to find some matches and have them put into a list when...
9
380
by: MJ | last post by:
HI I want to know what is mean by regular expression in C Mayur
10
3037
by: Lee Kuhn | last post by:
I am trying the create a regular expression that will essentially match characters in the middle of a fixed-length string. The string may be any characters, but will always be the same length. In other words, as the regular expression (....)($) matches the "4567" in the string "1234567", how would I create a similar regular expression that only matches the "45" in the same string. The same regular expression would match "32" in the string...
5
1640
by: Tony Marston | last post by:
I am seeking help with a regular expression that will split a string into several parts with ',' (comma) as the separator, but NOT where the separator is enclosed in parentheses. For example, take the string "field1, CONCAT(field2,' ', field3) as field23, field4". I would like to be able to split this into the following: field1 CONCAT(field2,' ', field3) as field23 field4 Thanks in advance.
9
3358
by: Pete Davis | last post by:
I'm using regular expressions to extract some data and some links from some web pages. I download the page and then I want to get a list of certain links. For building regular expressions, I use an app call The Regulator, which makes it pretty easy to build and test regular expressions. As a warning, I'm real weak with regular expressions. Let's say my regular expression is:
7
2098
by: Eric McGraw | last post by:
In Firefox, as in most regular expression engines, the split function works like this: > "His name is <name>. His email address is <email>.".split(/<(.*?)>/) returns so that the text pattern in the parentheses is included in the result. In Internet Explorer, however, the result is different:
12
2492
by: FAQEditor | last post by:
Anybody have any URL's to tutorials and/or references for Regular Expressions? The four I have so far are: http://docs.sun.com/source/816-6408-10/regexp.htm http://en.wikipedia.org/wiki/Regular_expression http://www.regular-expressions.info/javascript.html http://www.webreference.com/js/column5/
8
3434
by: mw | last post by:
Hello, I am trying to make a regex for a 12 hour clock, and I can't seem to get it just right. What I have now is var regexmatch = /(1:|:)\s((a\.m\.)|(p \.m\.))/i
0
10146
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10080
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9942
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7492
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6733
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5378
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5509
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4043
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3639
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.