如何仅选择第一个破折号 -
且位于空格之前?
你好 - 那是我的 - 第一个世界
我编写的正则表达式.+?(?=-)
选择了HEllo Good - That is my
。
如果我只有字符串 HEllo Good - That is my
,它看起来不错,但有空格。
var string = 'HEllo Good - That is my - first world';
console.log(string.match(/.+?(?=-)/gm));
最佳答案
如果您仅需要第一个破折号,只需使用输入^
的开头匹配字符串即可:
const text = 'HEllo Good - That is my - first world';
const pattern = /^.*?\s(-)/;
const match = text.match(pattern);
console.log(`full match: ${match[0]}`);
console.log(`dash only: ${match[1]}`)
如果您需要之前的内容,包括/排除第一个破折号:
const text = 'HEllo Good - That is my - first world';
const patternIncludeDash = /(^.*?\s-)/;
const patternExcludeDash = /(^.*?\s)-/;
console.log('before the dash, but include dash: ' + text.match(patternIncludeDash)[1]);
console.log('before the dash, but exclude dash: ' + text.match(patternExcludeDash)[1]);
关于javascript - 仅使用 JavaScript 中的正则表达式选择第一个破折号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51113181/