You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写正则表达式去除以.开头、Zacher结尾字符串的前后缀

Fixing Your Regex to Extract the Middle String

Hey there! Let's break down why your current regex isn't doing what you want, then fix it properly.

The Problem with Your Current Regex

Your regex /(?:.)|(?:Zacher)/ has two key issues:

  1. The . is a regex metacharacter that matches any single character, not the literal dot at the start of your string. You need to escape it with a backslash: \..
  2. You're missing the global flag (g), so the regex only replaces the first match it finds (the leading dot) and ignores the trailing Zacher. Also, there's no position anchoring, so it would match Zacher anywhere in the string instead of just the end.

Solution 1: Replace the Leading Dot and Trailing Zacher

Use a regex that specifically targets the leading dot (anchored to the start with ^) and the trailing Zacher (anchored to the end with $), plus the global flag to replace both:

// Example usage
const testStrings = [".mobileZacher", ".carZacher", ".StevenZacher"];
testStrings.forEach(str => {
  const result = str.replace(/^\.|Zacher$/g, '');
  console.log(result); // Outputs: mobile, car, Steven
});

Solution 2: Extract the Middle Part Directly (More Reliable)

Since you know all your strings follow the strict pattern .[content]Zacher, using a capture group to grab the middle content is even better—it avoids replacement entirely and gets straight to the value you want:

const str = ".StevenZacher";
const match = str.match(/^\.(.*)Zacher$/);
// Check if the match exists (in case of invalid input)
const result = match ? match[1] : '';
console.log(result); // Outputs: Steven

How This Works

  • ^ anchors the regex to the start of the string, so ^\. only matches a dot at the very beginning.
  • (.*) captures any sequence of characters (the content you want) into a group.
  • Zacher$ anchors the regex to the end of the string, so it only matches Zacher at the very end.
  • The match method returns an array where the first index is the full match, and index 1 is the captured content.

内容的提问来源于stack exchange,提问作者Denis Stephanov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:55:33