正则表达式实现:取分隔符左侧非空串,否则取右侧
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 grabbingabcfromabc|123) - Extract the part after the
|delimiter if the first part is empty (like grabbing123from|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)
- First branch:
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,$1will hold123and$2is empty, so replacing gives123 - For
abc|123,$2will holdabcand$1is empty, so replacing givesabc
内容的提问来源于stack exchange,提问作者ryanmcallister
相关产品推荐
相关产品推荐

