How to replace a substring only once?

129 views Asked by At

I have the following string:

Log First Meal Time,Twitter,Midday Routines Done,Midday Routines

I want to write a regular expression such that I will get exactly the following:

Log First Meal Time,Twitter,Midday Routines Done,⚡ Midday Routines

How to do it with some Regex that will only match the second occurrence of Midday Routines in this case?

I was replacing the Midday Routines with ⚡ Midday Routines, but it seems iPhone Shortcuts by default replace all occurrences, and I got:

Log First Meal Time,Twitter,⚡ Midday Routines Done,⚡ Midday Routines

I am new to regular expression and I have no ideas...

Please help! Thank you in advance.

4

There are 4 answers

0
NetMage On BEST ANSWER

In IOS Shortcuts, you should be able to use ICU Regex.

For Match, use: (Midday Routines)(.*?)\1

For Replace, use: $1$2⚡ $1

0
WJS On

You didn't specify a language. Here is one way to do it in Java.

Use String.replaceFirst.

  • () capture group
  • .*? - reluctant quantifier
  • $n back reference to the captured strings.
  • First capture group is the first occurrence plus everything just before the second occurrence.
  • Second capture group is the second occurrence.
String s = "Log First Meal Time,Twitter,Midday Routines Done,Midday Routines"; 
s = s.replaceFirst("(Midday Routines.*?)(Midday Routines)", "$1\u26A1 $2");
System.out.println(s);

prints

Log First Meal Time,Twitter,Midday Routines Done,⚡ Midday Routines

The above will work regardless of what comes after your initial string.

0
Dillion On

From what I understand, you want to match the last string after the last comma.

Here's the regex:

(?<=,)[^,]*$

Explanation:

  • (?<=,): lookbehind that verifies that there's a comma before the string
  • [^,]*: negated character class with quantifier that specifies - "match every other characters multiple times except a comma"
  • $: anchor that specifies that this pattern should end the sentence

So this pattern ensures that a comma precedes the string, and there's no comma after the preceded comma, and this is at the end of the sentence. This way, you match only the last string that doesn't have any comma after it.

Verify here

0
Peter Thoeny On

Your question is not well defined. From you comment it looks like you want to insert a character after the last comma in the string.

You can do that with with lookarounds:

(?<=,)(?=[^,]+$)

Explanation:

  • (?<=,) -- positive lookbehind for a comma
  • (?=[^,]+$) -- positive lookahead for anything not a comma until end of string

You did not specify the language. In JavaScript you would do a replace:

'Log First Meal Time,Twitter,Midday Routines Done,Midday Routines'.replace(/(?<=,)(?=[^,]+$)/, '⚡ ')
// returns: 'Log First Meal Time,Twitter,Midday Routines Done,⚡ Midday Routines'

Learn more about regex: https://twiki.org/cgi-bin/view/Codev/TWikiPresentation2018x10x14Regex