REGEXP_REPLACE使用问题:替换指定字符串后的全部内容(含换行)
Let's break down why your current regex isn't doing what you want, and get you the correct solution step by step.
The Issue with Your Current Regex
You used (best regards)[\w\W]* — this does match "best regards" plus everything that comes after it (including newlines, since [\w\W] covers all characters). But if you're replacing the entire match with just someone, you're wiping out "best regards" along with the rest of the content. That's why you're losing the phrase instead of keeping it intact.
Solution 1: Capture and Preserve "best regards"
We'll use a capture group to hold onto "best regards", then replace everything after it with "someone". Here's how to structure it:
Regex Pattern:
(best regards)[\s\S]*
(Note: [\s\S] works the same as [\w\W] — both match every character, including newlines. Pick whichever feels more intuitive to you.)
Replacement String:
\1 someone
(The \1 refers to the first capture group (which is "best regards"), so we keep that phrase and append "someone" right after it.)
Example Code (MySQL)
SELECT REGEXP_REPLACE( 'I will send you the parcel today. best regards (may contain multiple new lines) Tom', '(best regards)[\\s\\S]*', '\\1 someone' ) AS updated_string;
Note: In SQL, backslashes need to be escaped with an extra \, so [\s\S] becomes [\\s\\S].
Solution 2: Use Positive Lookbehind (For Supported Tools/Databases)
If your database or regex engine supports positive lookbehind (like MySQL 8.0+, PostgreSQL, or modern scripting tools), you can target only the content after "best regards" without capturing the phrase itself:
Regex Pattern:
(?<=best regards)[\s\S]*
(The (?<=...) is a positive lookbehind — it checks that "best regards" comes right before the content we want to replace, but doesn't include the phrase in the match.)
Replacement String:
someone
(We add a space here to match the original spacing between "best regards" and the following content.)
Example Code (MySQL 8.0+)
SELECT REGEXP_REPLACE( 'I will send you the parcel today. best regards (may contain multiple new lines) Tom', '(?<=best regards)[\\s\\S]*', ' someone' ) AS updated_string;
Either solution will give you your desired output:
I will send you the parcel today. best regards someone
内容的提问来源于stack exchange,提问作者newbie

