Java如何在空格或'-'前后有字符时使用split()分割字符串
Got it, let's tackle this problem exactly as you described: you want to split a string only when there's a - or space that has characters both before and after it. Leading/trailing separators (like a space at the start, - at the end) shouldn't trigger a split—only the ones sandwiched between actual characters count.
The Regex Approach
The perfect tool here is a regular expression with lookaround assertions—they let us check what's before/after the separator without including those characters in the match. Here's the pattern we'll use:
(?<=\S)[- ](?=\S)
Let's break down what each part does:
(?<=\S): A positive lookbehind that ensures the character immediately before our separator is a non-whitespace character (\S= any character that's not a space/tab/newline)[- ]: Matches either a-or a space (we put-first in the character set to avoid it being interpreted as a range)(?=\S): A positive lookahead that ensures the character immediately after our separator is also a non-whitespace character
Example Code (Python)
Here's how you can implement this in Python:
import re def split_on_valid_separators(input_str): # Split using our regex pattern return re.split(r'(?<=\S)[- ](?=\S)', input_str) # Test all your example cases test_cases = [ " test", "-test", "test test", " test test", "test-", "test-test", "a-test" ] for case in test_cases: result = split_on_valid_separators(case) print(f"Input: '{case}' → Output: {result}")
Test Output:
Input: ' test' → Output: [' test'] Input: '-test' → Output: ['-test'] Input: 'test test' → Output: ['test', 'test'] Input: ' test test' → Output: [' test', 'test'] Input: 'test-' → Output: ['test-'] Input: 'test-test' → Output: ['test', 'test'] Input: 'a-test' → Output: ['a', 'test']
Example Code (JavaScript)
If you're working in JavaScript, the logic is identical—just use the same regex with split():
function splitOnValidSeparators(inputStr) { return inputStr.split(/(?<=\S)[- ](?=\S)/); } // Test cases const testCases = [ " test", "-test", "test test", " test test", "test-", "test-test", "a-test" ]; testCases.forEach(case => { const result = splitOnValidSeparators(case); console.log(`Input: '${case}' → Output: ${JSON.stringify(result)}`); });
Key Notes
- This approach preserves any leading/trailing whitespace or separators in your input string, since we're only splitting on the valid middle separators.
- If you need to handle other whitespace characters (like tabs or newlines), replace the space in the regex with
\s(which matches any whitespace), making the pattern(?<=\S)[-\s](?=\S).
内容的提问来源于stack exchange,提问作者dechiic

