473,378 Members | 1,482 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

How to make a c# regex match only the *last* occurrence of a pattern?

Hi,

I've been searching as best I can for this - coming up with little.

I have a file that is full of lines fitting this pattern:

(?<year>\d{4}),(?<amount>\d{6,7})

I'm likely to get a bunch of hits with this - I'm only interested in
the *last* one. Is there a way to build the concept "last" into the
regex itself? Or is taking the last element of the match array the only
thing to do?

I would just prefer to avoid have a potentially long array being sent
around...

Thanks,

cdj

Nov 8 '06 #1
8 10245
One suggestion is to find the last index of the newline character, and regex
everything after that, if now match, last index it again on everything before
it and they the reg ex on that line. you could keep doing this till a match
occurs. I'm not a regex expert but I dont believe you can specify the last
match.

HTH

Ciaran

"sherifffruitfly" wrote:
Hi,

I've been searching as best I can for this - coming up with little.

I have a file that is full of lines fitting this pattern:

(?<year>\d{4}),(?<amount>\d{6,7})

I'm likely to get a bunch of hits with this - I'm only interested in
the *last* one. Is there a way to build the concept "last" into the
regex itself? Or is taking the last element of the match array the only
thing to do?

I would just prefer to avoid have a potentially long array being sent
around...

Thanks,

cdj

Nov 9 '06 #2
Hi,

You can find what you want by searching for the occurrence of your
pattern that does not have _another_ occurrence of that pattern after
it.

Suppose your pattern is P. You can search for the last P by doing a
search for "anything" followed by "P" followed by "anything but P".

Or you can try google (d'oh, right? :D "pattern matching c# last"):

http://www.google.nl/search?hs=ue5&h...G=Zoeken&meta=

In short, the solution presented at the first hit from google is to use
the RegexOptions.RightToLeft parameter :P

-Jeroen

Nov 9 '06 #3
Like I said, I'm no regex guru so I offered a coding way round it. The regex
option is undoubtedly better.

Ciaran O'Donnell

"Jeroen" wrote:
Hi,

You can find what you want by searching for the occurrence of your
pattern that does not have _another_ occurrence of that pattern after
it.

Suppose your pattern is P. You can search for the last P by doing a
search for "anything" followed by "P" followed by "anything but P".

Or you can try google (d'oh, right? :D "pattern matching c# last"):

http://www.google.nl/search?hs=ue5&h...G=Zoeken&meta=

In short, the solution presented at the first hit from google is to use
the RegexOptions.RightToLeft parameter :P

-Jeroen

Nov 9 '06 #4

Jeroen wrote:
Hi,

You can find what you want by searching for the occurrence of your
pattern that does not have _another_ occurrence of that pattern after
it.

Suppose your pattern is P. You can search for the last P by doing a
search for "anything" followed by "P" followed by "anything but P".

Or you can try google (d'oh, right? :D "pattern matching c# last"):
Which I did long before I posted the question. I saw the right-to-left
trick. I was simply hoping for a "pure regex solution", rather than an
implementation-specific solution.

I'll see if I can get your first idea to work for me though - thanks a
bunch!

cdj

Nov 9 '06 #5
In article <11**********************@k70g2000cwa.googlegroups .com>,
sherifffruitfly <sh*************@gmail.comwrote:

: I have a file that is full of lines fitting this pattern:
:
: (?<year>\d{4}),(?<amount>\d{6,7})
:
: I'm likely to get a bunch of hits with this - I'm only interested in
: the *last* one. Is there a way to build the concept "last" into the
: regex itself? Or is taking the last element of the match array the only
: thing to do?
:
: I would just prefer to avoid have a potentially long array being sent
: around...

Start your pattern with .* to grab the last match. For example:

using System;
using System.Text.RegularExpressions;

namespace consapp
{
class Program
{
static void Main(string[] args)
{
const string pattern = @"(?<year>\d{4}),(?<amount>\d{6,7})";
Regex regex;
Match m;
string input = "1234,1234569999,123456";

Console.WriteLine("Vanilla pattern:");
regex = new Regex(pattern);
m = regex.Match(input);
Console.WriteLine(" - year=[{0}], amount={1}",
m.Groups["year"], m.Groups["amount"]);

Console.WriteLine("Leading dot-star:");
regex = new Regex(".*" + pattern);
m = regex.Match(input);
Console.WriteLine(" - year=[{0}], amount={1}",
m.Groups["year"], m.Groups["amount"]);
}
}
}

Output:

Vanilla pattern:
- year=[1234], amount=1234569
Leading dot-star:
- year=[9999], amount=123456

Hope this helps,
Greg
--
Criminal means, once tolerated, are soon preferred.
-- Edmund Burke
Nov 20 '06 #6

Greg Bacon wrote:
>
Start your pattern with .* to grab the last match. For example:
Thank you!

Nov 21 '06 #7
sherifffruitfly wrote:
Which I did long before I posted the question. I saw the right-to-left
trick. I was simply hoping for a "pure regex solution", rather than an
implementation-specific solution.

I'll see if I can get your first idea to work for me though - thanks a
bunch!
Well, it might have been a good idea to mention this - something like
"I know about the right-to-left flag, but I want a portable solution."

Fwiw, while using .* to skip to the end and work backward should be
pretty fast, it will only let you find the last match. Using the
right-to-left flag will let you quickly find the last N matches.

--

www.midnightbeach.com/.net
What you need to know.
Nov 21 '06 #8

Jon Shemitz wrote:
sherifffruitfly wrote:
Which I did long before I posted the question. I saw the right-to-left
trick. I was simply hoping for a "pure regex solution", rather than an
implementation-specific solution.
Well, it might have been a good idea to mention this - something like
"I know about the right-to-left flag, but I want a portable solution."
Sigh.

You DON'T google before asking, and you get reamed.

You DO google before asking, and still get reamed.
Thanks.

Nov 21 '06 #9

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

Similar topics

7
by: alphatan | last post by:
Is there relative source or document for this purpose? I've searched the index of "Mastering Regular Expression", but cannot get the useful information for C. Thanks in advanced. -- Learning...
2
by: Daniel Billingsley | last post by:
First, if MSFT is listening I'll say IMO the MSDN material is sorely lacking in this area... it's just a whole bunch of information thrown at you and you're left to yourself as to organizing it in...
4
by: shonend | last post by:
I am trying to extract the pattern like this : "SUB: some text LOT: one-word" Described, "SUB" and "LOT" are key words; I want those words, everything in between and one word following the...
3
by: gisleyt | last post by:
I'm trying to compile a perfectly valid regex, but get the error message: r = re.compile(r'(*)(\d{1,3}\.\d{0,2})?(\d*)(\,\d{1,3}\.\d{0,2})?(\d*)?.*') Traceback (most recent call last): File...
10
by: Extremest | last post by:
I know there are ways to make this a lot faster. Any newsreader does this in seconds. I don't know how they do it and I am very new to c#. If anyone knows a faster way please let me know. All...
1
by: Prabhu Gurumurthy | last post by:
Hello all - I have a file which has IP address and subnet number and I use regex to extract the IP separately from subnet. pattern used for IP: \d{1,3}(\.\d{1,3}){3} pattern used for...
3
by: MCH | last post by:
hi there, I am working with a HTML-like text with boost:regex. For example, the following pattern might occur in my text <abc efg> <p>EFG</p 12<3> In this case, I would like to extract...
11
by: proctor | last post by:
hello, i have a regex: rx_test = re.compile('/x()*x/') which is part of this test program: ============ import re
2
by: John B | last post by:
I am trying to do a pretty simple pattern match using regex. The pattern is ^(?:(?<Item>.*?)@:@)*$. This should return a match for test123@:@ but does not, instead it never returns when I call...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.