Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

javascript - Using regex to replace only the last occurrence of a pattern with JS

I have a case where I'm trying to replace a certain pattern with another. My problem is that I need to only replace the last occurrence of that pattern, not all of them. I've found this question:

How to replace last occurrence of characters in a string using javascript

But it doesn't fit my needs. As a background, I will say that I am trying to replace a CSS rule, but for the current example lets look at this text:

abcd:bka:

bbb:aad:

accx:aaa:

bbb:a0d:

cczc:aaa:

lets say I only want to replace the value of bbb. My current rule will be

text.replace(/(s*bbb:)([^:]+)/,"$1aaa")

but it will only replace the first match, while I want it to replace the last one. My current pattern is actually more complex than this one, but I think the pseudo problem will suffice.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try

text.replace(/(s*bbb:)(?![sS]*bbb:)[^:]+/,"$1aaa")

The negative lookahead assertion makes sure that there is no further bbb: ahead in the text. The parentheses around [^:]+ are unnecessary.

Explanation:

(?!       # Assert that it is impossible to match the following after the current position:
 [sS]*  # any number of characters including newlines
 bbb:     # the literal text bbb:
)         # End of lookahead assertion

The [sS] workaround is necessary because JavaScript doesn't have an option to allow the dot to match newlines.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...