如何-
仅在空格之前选择第一个破折号?
HEllo Good - That is my - first world
我写的正则表达式.+?(?=-)
选择了HEllo Good - That is my
.
如果我只有 string 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]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句