473,750 Members | 2,669 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Regular Expression - Match all except last one

I know that the /g flag will match all occurrences. Is there a way, with
a Regular Expression, to match all occurrences *except* the last one?

pattern = /df/g;
var myString = "asdfasdfasdfas df";
var newString = myString.replac e(pattern,'gh') ;
alert(newString )

Gives me: asghasghasghasg h as it should.
What I want: asghasghasghasd f Where the last one is not replaced.

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Mar 19 '06 #1
17 11669
> "Randy Webb" <Hi************ @aol.com> wrote:
news:Q7******** ************@co mcast.com....

I know that the /g flag will match all occurrences. Is there a way,
with a Regular Expression, to match all occurrences *except* the
last one?

pattern = /df/g;
var myString = "asdfasdfasdfas df";
var newString = myString.replac e(pattern,'gh') ;
alert(newString )

Gives me: asghasghasghasg h as it should.
What I want: asghasghasghasd f Where the last one is not replaced.


Does the string always end with the pattern?

--
BootNic Sunday, March 19, 2006 1:19 AM

It's not that some people have willpower and some don't. It's that
some people are ready to change and others are not.
*James Gordon*

Mar 19 '06 #2
BootNic said the following on 3/19/2006 1:20 AM:
"Randy Webb" <Hi************ @aol.com> wrote:
news:Q7******** ************@co mcast.com....

I know that the /g flag will match all occurrences. Is there a way,
with a Regular Expression, to match all occurrences *except* the
last one?

pattern = /df/g;
var myString = "asdfasdfasdfas df";
var newString = myString.replac e(pattern,'gh') ;
alert(newString )

Gives me: asghasghasghasg h as it should.
What I want: asghasghasghasd f Where the last one is not replaced.


Does the string always end with the pattern?


Yes. And I think I know where you are headed but I will wait and see :)

The pattern I am actually matching is \r\n and the string is the .value
of a textarea. It is replacing it with ";\r\ndocument. write("
Where the " is part of the replacement. All it does is take code and
create document.write statements for them. What I end up with at the end
is an extra document.write( " that I don't want.

I could always just replace the last occurence of document.write( " but I
was hoping there was a simpler solution.
--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Mar 19 '06 #3
> "Randy Webb" <Hi************ @aol.com> wrote:
news:qZ******** ************@co mcast.com....

BootNic said the following on 3/19/2006 1:20 AM:
"Randy Webb" <Hi************ @aol.com> wrote:
news:Q7******** ************@co mcast.com....

I know that the /g flag will match all occurrences. Is there a
way, with a Regular Expression, to match all occurrences *except*
the last one?

pattern = /df/g;
var myString = "asdfasdfasdfas df";
var newString = myString.replac e(pattern,'gh') ;
alert(newString )

Gives me: asghasghasghasg h as it should.
What I want: asghasghasghasd f Where the last one is not replaced.


Does the string always end with the pattern?


Yes. And I think I know where you are headed but I will wait and
see :)

The pattern I am actually matching is \r\n and the string is the
.value of a textarea. It is replacing it with ";\r\ndocument. write("
Where the " is part of the replacement. All it does is take code and
create document.write statements for them. What I end up with at
the end is an extra document.write( " that I don't want.

I could always just replace the last occurence of document.write( "
but I was hoping there was a simpler solution.


Well now, I don't think I am comprehending the situation. It sounds like
you need to strip the the white space on each end of the sting before the
replace.

But I don't think that is the issue.

I was going to suggest one of two things.

pattern = /df(?=.)/g;
var myString = "asdfasdfasdfas df";
var newString = myString.replac e(pattern,'gh') ;
alert(newString );

Or

var myString = "asdfasdfasdfas df";
while(myString. match(/df/g).length!=1){
myString=myStri ng.replace(/df/,'gh')
}
alert(myString) ;

--
BootNic Sunday, March 19, 2006 2:21 AM

Get your facts first, and then you can distort them as much as you
please.
*Mark Twain *

Mar 19 '06 #4
Randy Webb wrote:
I know that the /g flag will match all occurrences. Is there a way, with
a Regular Expression, to match all occurrences *except* the last one?

pattern = /df/g;
var myString = "asdfasdfasdfas df";
var newString = myString.replac e(pattern,'gh') ;
alert(newString )

Gives me: asghasghasghasg h as it should.
What I want: asghasghasghasd f Where the last one is not replaced.


var newString = myString.replac e(/df(.)/g,'gh$1');

--
Mar 19 '06 #5
Alexander Bartolich said the following on 3/19/2006 4:33 PM:
Randy Webb wrote:
I know that the /g flag will match all occurrences. Is there a way, with
a Regular Expression, to match all occurrences *except* the last one?

pattern = /df/g;
var myString = "asdfasdfasdfas df";
var newString = myString.replac e(pattern,'gh') ;
alert(newString )

Gives me: asghasghasghasg h as it should.
What I want: asghasghasghasd f Where the last one is not replaced.


var newString = myString.replac e(/df(.)/g,'gh$1');


What do the (.) and $1 do? The code does exactly what I want it to do
but I want to understand it now.

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Mar 19 '06 #6
JRS: In article <qZ************ ********@comcas t.com>, dated Sun, 19 Mar
2006 02:04:22 remote, seen in news:comp.lang. javascript, Randy Webb
<Hi************ @aol.com> posted :
The pattern I am actually matching is \r\n and the string is the .value
of a textarea. It is replacing it with ";\r\ndocument. write("
Where the " is part of the replacement. All it does is take code and
create document.write statements for them. What I end up with at the end
is an extra document.write( " that I don't want.

I could always just replace the last occurence of document.write( " but I
was hoping there was a simpler solution.


Append the string '") ;' and you have effectively neutralised it.

Or can you pre-process myString with a .replace that removes just the
final \r\n? Or chop off the last 2 characters with substr or substring?
OTOH, can you not replace \r\n(.) with ";\r\ndocument. write("$1
which should not see a final \r\n ? Untested.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Mar 19 '06 #7
Dr John Stockton said the following on 3/19/2006 6:35 PM:
JRS: In article <qZ************ ********@comcas t.com>, dated Sun, 19 Mar
2006 02:04:22 remote, seen in news:comp.lang. javascript, Randy Webb
<Hi************ @aol.com> posted :
The pattern I am actually matching is \r\n and the string is the .value
of a textarea. It is replacing it with ";\r\ndocument. write("
Where the " is part of the replacement. All it does is take code and
create document.write statements for them. What I end up with at the end
is an extra document.write( " that I don't want.

I could always just replace the last occurence of document.write( " but I
was hoping there was a simpler solution.
Append the string '") ;' and you have effectively neutralised it.


That is, to date, the best suggestion I have seen/read :) I already
prepend document.write( ' to it so appending isn't a big deal.
Or can you pre-process myString with a .replace that removes just the
final \r\n? Or chop off the last 2 characters with substr or substring?
That was also something I considered. Check to see if the last two are
\r\n (is that 2 or 4 characters?) and go from there. I need to do
different things if there is a final \r\n with no text following it.

Something else I considered was adding a final \r\n and then remove any
empty document.write statements (just so they aren't there, they won't
hurt anything).
OTOH, can you not replace \r\n(.) with ";\r\ndocument. write("$1
which should not see a final \r\n ? Untested.


It doesn't work correctly if there is a final \r\n in the string.

delim = /\r\n(.)/g;
output.value="d ocument.write(' "+input.value.r eplace(delim,'\ ');\ndocument.w rite\(\'$1');

output and input are references to a textarea.
If the final line of the input is an empty line, where you type in text
and then press the Enter key with no more text, it breaks horribly. As
long as there is no \r\n at the very end of the string, it works perfectly.
--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/

Mar 20 '06 #8
Randy Webb wrote:
Alexander Bartolich said the following on 3/19/2006 4:33 PM:
[...]
var newString = myString.replac e(/df(.)/g,'gh$1');


What do the (.) and $1 do? The code does exactly what I want
it to do but I want to understand it now.


The dot matches any character.
The round brackets form a parenthesized subexpression.
The text matched by such subexpression is available in the
replacement text as $1, $2, $3, etc.

So what this does is to search for "df" followed by any character,
and replace that with "gh", followed by that character.

--
post tenebras lux. post fenestras tux.
Mar 20 '06 #9
Alexander Bartolich said the following on 3/20/2006 3:03 AM:
Randy Webb wrote:
Alexander Bartolich said the following on 3/19/2006 4:33 PM:
[...]
var newString = myString.replac e(/df(.)/g,'gh$1');

What do the (.) and $1 do? The code does exactly what I want
it to do but I want to understand it now.


The dot matches any character.
The round brackets form a parenthesized subexpression.
The text matched by such subexpression is available in the
replacement text as $1, $2, $3, etc.

So what this does is to search for "df" followed by any character,
and replace that with "gh", followed by that character.


Thank you for the code and the explanation. I guess it's finally time
for me to read my references on Regular Expressions, asking questions,
and learn the things.

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Mar 20 '06 #10

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

Similar topics

1
4179
by: Kenneth McDonald | last post by:
I'm working on the 0.8 release of my 'rex' module, and would appreciate feedback, suggestions, and criticism as I work towards finalizing the API and feature sets. rex is a module intended to make regular expressions easier to create and use (and in my experience as a regular expression user, it makes them MUCH easier to create and use.) I'm still working on formal documentation, and in any case, such documentation isn't necessarily the...
4
3228
by: Neri | last post by:
Some document processing program I write has to deal with documents that have headers and footers that are unnecessary for the main processing part. Therefore, I'm using a regular expression to go over each document, find out if it contains a header and/or a footer and extract only the main content part. The headers and the footers have no specific format and I have to detect and remove them using a list of strings that may appear as...
3
3331
by: LordHog | last post by:
Hello all, I am attempting to create a small scripting application to be used during testing. I extract the commands from the script file I was going to tokenize the each line as one of the requirements is there one command per line. I have always wanted to learn Regular Expressions, so I was hoping I might do this using Regular Expressions. For a fair number of the command will have the syntax like Write( 0x123, 0x12, 25, 100 ) <-...
3
2565
by: Zach | last post by:
Hello, Please forgive if this is not the most appropriate newsgroup for this question. Unfortunately I didn't find a newsgroup specific to regular expressions. I have the following regular expression. ^(.+?) uses (?!a spoon)\.$
5
2288
by: Cylix | last post by:
I am going to write a function that the search engine done. in search engine, we may using double quotation to specify a pharse like "I love you", How can I using regular expression to sperate each pharse? test case: "I love" all "of you" I would like it return:
25
5165
by: Mike | last post by:
I have a regular expression (^(.+)(?=\s*).*\1 ) that results in matches. I would like to get what the actual regular expression is. In other words, when I apply ^(.+)(?=\s*).*\1 to " HEART (CONDUCTION DEFECT) 37.33/2 HEART (CONDUCTION DEFECT) WITH CATHETER 37.34/2 " the expression is "HEART (CONDUCTION DEFECT)". How do I gain access to the expression (not the matches) at runtime? Thanks, Mike
5
2319
by: Avi Kak | last post by:
Folks, Does regular expression processing in Python allow for executable code to be embedded inside a regular expression? For example, in Perl the following two statements $regex = qr/hello(?{print "saw hello\n"})mello(?{print "saw mello\n"})/; "jellohellomello" =~ /$regex/;
6
9059
by: Peter Duniho | last post by:
So, I'm trying to learn how the Regex class works, and I've been trying to use it to do what I think ought to be simple things. Except I can't figure out how to do everything I want. :( If I want to take a string and break it into individual lines based on a specific pattern ("\r\n" in this case, but I don't think it matters), I can easily write a loop that does this by scanning through the string accumulating characters and spitting...
1
4812
by: Mr.SpOOn | last post by:
Hi, I've never used exception before, but I think now it's time to start. I've seen that there is a list of the built-in exceptions in the Python docs, but this explains the meaning of every exception. Does exist an inverted list? I mean, how may I know what kind of exception is going to raise my code? Shall I figure out by myself? Apart from this, in a method I check valid strings with a regular expression. I pass the string to the...
0
9583
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9396
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
9342
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
9256
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...
0
8263
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6808
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
4716
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
4888
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2807
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.