我正在尝试使用RegExp,以便稍后可以插入字符串变量。但是,即使没有该变量的第一次尝试也将不起作用。缺少什么?
有一个很好的jsbin链接可以显示行为。
const DOCS = [
"My Report – March 2019.pdf",
"My Report – May 2019.pdf",
"My Diary - April-May 2019.pdf",
"My Diary - February-March 2019.pdf"
]
const title_month_year = new RegExp("(.*) - (January|February|March|April|May|June|July|August|September|October|November|December) (19|20\d{2})")
DOCS.forEach(
mag = mag.replace(/–/g, "-");
// if (title_month_year.test(mag)) { <--- does not match
if (/(.*) - (January|February|March|April|May|June|July|August|September|October|November|December) (19|20\d{2})/.test(mag)) {
console.log('we have a match');
}
答案 0 :(得分:1)
const DOCS = [
"My Report – March 2019.pdf",
"My Report – May 2019.pdf",
"My Diary - April-May 2019.pdf",
"My Diary - February-March 2019.pdf"
]
const months = {
"January": "01",
"Jan": "01",
"February": "02",
"Feb": "02",
"March": "03",
"Mar": "03",
"April": "04",
"Apr": "04",
"May": "05",
"June": "06",
"Jun": "06",
"July": "07",
"Jul": "07",
"August": "08",
"Aug": "08",
"September": "09",
"Sep": "09",
"October": "10",
"Oct": "10",
"November": "11",
"Nov": "11",
"December": "12",
"Dec": "12"
}
let docsCopy = DOCS.map(m => {
var mReplace = m.replace(/^(.+)+(?:\s[-–]\s)+((?:\w+)+(?:-)?(?:\w+)?)+\s(\d+)+(.+)/, (match, p1, p2, p3, p4) => {
var reg = /(\w+)?(?:[-–](\w+))?/
var p2C = p2.replace(reg, (match, $1, $2) => {
var p2Months = $2 ? [months[$1], months[$2]] : [months[$1]]
return p2Months.join('-')
})
return p1 + ' ' + p3 + '-' + p2C + p4
})
return mReplace
});
console.log(docsCopy)
答案 1 :(得分:0)
正如第四只鸟所指出的,您正在使用另一种类型的hypen。
您可以做的就是调整您的正则表达式,使其包含两种类型的连字符:
const title_month_year = new RegExp("(.*) (-|–) (January|February|March|April|May|June|July|August|September|October|November|December) (19|20\d{2})")
请注意,在解决方案中,您的分组值将在第一个条目之后偏移一个(因此,现在您不再拥有3个元素,而是3个,第一个是hypen前面的内容,第二个是hypen类型,第三个是月份,第四个是年份。
或者只是寻找一个字符而不是一个连字符:
const title_month_year = new RegExp("(.*) . (January|February|March|April|May|June|July|August|September|October|November|December) (19|20\d{2})")
答案 2 :(得分:0)
您忘了逃避\ d {2}
它应该在RegExp字符串内\\ d {2}。