Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex replacement issues

Tags:

regex

https://www.myregextester.com/?r=6fba8b94

Regex is

(\w(s)\b)

Sample Word

Dress
  • \1 returns "Dress"
  • \2 returns "Dres"

So I figured:

  • \1 \2 would return "Dress Dres"

But it returns:

"Dress s"

How can I make it return "Dress Dres"

like image 635
user3649739 Avatar asked Dec 22 '25 02:12

user3649739


2 Answers

You're misreading something in that regex tester. In reality, \1 is equal to ss and \2 is equal to s. This is because you are only matching two characters, \w and s. Even if you added a 1+ quantifier to the \w (i.e. (\w+(s)\b)), you'd still just match Dress and s, since the second capture group is literally just capturing the s.


If you move those capture groups around a bit, you can successfully capture "Dress" and "Dres". A quick side note, you can get the entire regex match with \0 so the nested capture groups are somewhat unnecessary here.

Match: (\w+)s\b

Replace: \0 \1

Output: Dress Dres

like image 133
Sam Avatar answered Dec 24 '25 02:12

Sam


First, use a + quantifier with \w to match 1 or more word characters (you only match 1 with \w). That is why you get just s and s (see your regex in action capturing ss as Group 1 and s as Group 2).

And use:

(\w+)s\b

With \0 \1 replacement where \0 backreferences the whole match, and the \1 backreferences what was captured with (\w+). See demo here.

Or, if it is Perl, use ((\w+)s)\b and replace with \1 \2 (see demo).

See demo

like image 26
Wiktor Stribiżew Avatar answered Dec 24 '25 02:12

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!