正则表达式匹配:排除CN开头变更通知ID的全部内容
Solution to Filter Out CN-Prefixed Entries from Comma-Separated String
Got it, let's break down how to solve this problem where you need to keep all entries in a comma-separated string except those with IDs starting with "CN". Each entry follows the format [ID]~-~[description], so we'll target the ID prefix specifically.
1. Using Regular Expressions (Quick Pattern Matching)
If you just need to extract valid entries directly, a regex can handle this in one go. The pattern will match any entry where the ID doesn't start with "CN":
(?:^|,)(?!CN)\w+~-~[^,]+
How it works:
(?:^|,): Matches the start of the string or a comma (captures the entry's leading separator without grouping it)(?!CN): Negative lookahead to ensure the next characters aren't "CN"\w+: Matches the alphanumeric ID (adjust to[\w\d]+if you need stricter digit/letter matching)~-~: Exact match for the separator between ID and description[^,]+: Matches everything until the next comma (the full description part)
Example Usage (JavaScript):
const input = "CN98765432~-~ECN for A01234 Rev A,CR00098765~-~ECR for A12345 SOME PART NAME,CN12345678~-~ECN for A12345 Rev A"; const validEntries = input.match(/(?:^|,)(?!CN)\w+~-~[^,]+/g)?.map(entry => entry.replace(/^,/, '')) || []; console.log(validEntries.join(',')); // Output: "CR00098765~-~ECR for A12345 SOME PART NAME"
2. Programmatic Filtering (More Readable for Code)
If you're working in a language like Python, splitting the string into entries and filtering is often more maintainable and easier to tweak:
Python Example:
input_str = "CN98765432~-~ECN for A01234 Rev A,CR00098765~-~ECR for A12345 SOME PART NAME,CN12345678~-~ECN for A12345 Rev A" # Split into individual entries entries = input_str.split(',') # Filter out entries where ID starts with "CN" valid_entries = [entry for entry in entries if not entry.split('~-~')[0].startswith('CN')] # Join back into a comma-separated string result = ','.join(valid_entries) print(result) # Output: "CR00098765~-~ECR for A12345 SOME PART NAME"
Why this works:
- Split the input string by commas to get each standalone entry
- For each entry, split on
~-~to isolate the ID portion - Check if the ID starts with "CN" — if not, keep the full entry
- Join the valid entries back into a single comma-separated string
Edge Cases to Consider
- Empty Entries: If your input might have trailing commas or empty strings, add a check to skip those:
if entry.strip() and not ... - Case Sensitivity: If lowercase "cn" should also be excluded, use
.lower().startswith('cn')instead - Non-Standard IDs: If IDs can include special characters, adjust the regex or split logic to match your actual ID format
内容的提问来源于stack exchange,提问作者Some One
相关产品推荐
相关产品推荐

