正则表达式匹配连字符前所有内容(多匹配且忽略空格)
Solution to Extract Hyphen-Prefix Substrings
The issue with your previous regex attempts comes down to not properly excluding spaces and ensuring we only target the part immediately before each hyphen in your space-separated tokens. Here's how to fix it:
Correct Regex Pattern
Use this regex with the global flag (g) to capture all desired substrings:
[^\s-]+(?=-)
Breakdown of the Pattern:
[^\s-]+: Matches one or more characters that are not whitespace (\s) or a hyphen (-). This ensures we only grab the part of each token before the hyphen, ignoring spaces between tokens.(?=-): A positive lookahead that confirms the matched sequence is immediately followed by a hyphen. This prevents matching any unrelated text that doesn’t have a hyphen after it.- Global flag (
g): Tells the regex engine to find all matches in the input string, not just the first one.
Why Your Previous Attempts Failed:
[^-]+: This matches any character except hyphen, which includes spaces and the text after hyphens until the next hyphen. For example, after the first hyphen, it would matchpsql11 scQA00instead of justscQA00.(.*?)(?=-)+: The lazy wildcard.*?matches any character (including spaces) until the first hyphen. Without the global flag, it stops at the first match. Even with the flag, it would include spaces and unwanted text between tokens.
Example Usage (JavaScript)
const inputString = "scQA00-psql11 scQA00-psql21 scQA01-psql2 scQA00-psql21 scqa00-psql01 scqa00-psql11 scqa00-psql21"; const regex = /[^\s-]+(?=-)/g; const results = inputString.match(regex); console.log(results); // Output: ["scQA00", "scQA00", "scQA01", "scQA00", "scqa00", "scqa00", "scqa00"]
This will give you exactly the list of substrings you’re looking for, preserving case sensitivity as in your input.
内容的提问来源于stack exchange,提问作者sero
相关产品推荐
相关产品推荐

