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

正则表达式实现:取分隔符左侧非空串,否则取右侧

Solution for Your Regex Conditional Extraction

Hey there! I totally get how tricky regex can feel when you're just starting out—conditional logic like this can definitely throw you for a loop. Let's break down exactly how to solve your problem step by step.

Core Requirement Recap

You want to:

  • Extract the part before the | delimiter if it's not empty (like grabbing abc from abc|123)
  • Extract the part after the | delimiter if the first part is empty (like grabbing 123 from |123)

The Regex & How It Works

The most reliable approach (works across most regex engines) uses branching capture groups to handle both cases:

^(?:([^|]+)\|.*|.*\|(.+))$

Let's break down what each piece does:

  • ^ & $: Anchor the regex to match the entire string (so we don't get partial matches)
  • (?: ... | ... ): A non-capturing group that holds our two conditional branches
    • First branch: ([^|]+)\|.*
      • ([^|]+): Captures one or more characters that aren't | (this is our first target value, stored in Group 1)
      • \|.*: Matches the delimiter and everything after it (we don't care about this part)
    • Second branch: .*\|(.+)
      • .*\|: Matches everything up to and including the delimiter (covers cases where the first part is empty)
      • (.+): Captures one or more characters after the delimiter (stored in Group 2)

How to Use It

When you run this regex against your string:

  • If the first part (before |) is non-empty, Group 1 will have your desired value, and Group 2 will be empty
  • If the first part is empty, Group 1 will be empty, and Group 2 will have your desired value

For example, in Python, you could implement this like so:

import re

def extract_target(input_str):
    match_result = re.match(r'^(?:([^|]+)\|.*|.*\|(.+))$', input_str)
    # Return Group 1 if it exists, else Group 2
    return match_result.group(1) if match_result.group(1) else match_result.group(2)

# Test cases
print(extract_target("abc|123"))  # Output: abc
print(extract_target("|123"))     # Output: 123
print(extract_target("xyz|7890")) # Output: xyz

Simplified Alternative (Using Replace)

If you're working with a tool that supports regex replacement (like text editors or some scripting languages), you can use this one-liner trick:

  • Find: ^(?:\|(.+)|(.+)\|.*)$
  • Replace with: $1$2

This works because:

  • For |123, $1 will hold 123 and $2 is empty, so replacing gives 123
  • For abc|123, $2 will hold abc and $1 is empty, so replacing gives abc

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 10:07:32