[英]Regular expression pattern to find a word in the delimited multiline string in javascript
I want the output as Test_guest1613 if the pattern is for Guest Name and AK004 if the pattern is for Room Number如果模式用于客人姓名,我希望output作为Test_guest1613 ,如果模式用于房间号,我希望 AK004
let mystring = `The description value is Holrest
Code: adip-345
Guest Name : Test_guest1613
Room Number: AK004
Request Number : 107157
Request Method: Email
Dates Requested:25-Jul-2020 08:00PM
If no specific date, weekday or weekend : N/A
Start Time:25-Jul-2020 08:00PM
Time Zone : ET `;
re=/Guest Name\s?:\s?(.*?)( |$)/g;
mystring.match(re);
gives me the array output Guest Name: Test_guest1613 but i want just want Test_guest1613给我数组 output 来宾名称:Test_guest1613 但我只想要 Test_guest1613
Use re.exec(mystring)
to collect captured groups and access the second in the array.使用
re.exec(mystring)
收集捕获的组并访问数组中的第二个。
let mystring = `The description value is Holrest Code: adip-345 Guest Name: Test_guest1613 Room Number: AK004 Request Number: 107157 Request Method: Email Dates Requested:25-Jul-2020 08:00PM If no specific date, weekday or weekend: N/A Start Time:25-Jul-2020 08:00PM Time Zone: ET `; re=/Code\s?:\s?(.*?)(?:\n| |$)+Guest Name\s?:\s?(.*?)(?: |$)/gm; let matches = re.exec(mystring); let code = matches[1]; let guestName = matches[2]; console.log(guestName, code);
You could remove Guest Name:
after the fact with .replace
.您可以删除
Guest Name:
事后使用.replace
。 IE: mystring.match(re).replace(/Guest Name\s?:\s?/)
IE:
mystring.match(re).replace(/Guest Name\s?:\s?/)
If you want both values for Guest Name
and Room Number
, you could use 2 capturing groups:如果您想要
Guest Name
和Room Number
的两个值,您可以使用 2 个捕获组:
^Guest Name\s?:\s?(.*?)\s*\r?\nRoom Number\s?:\s?(.*)
These are the separate pattern, for which you could use group 1 to get the value这些是单独的模式,您可以使用第 1 组来获取值
^Guest Name\s?:\s?(.*?)[^\S\r\n]*$
and ^Room Number\s?:\s?(.*?)[^\S\r\n]*$
^Guest Name\s?:\s?(.*?)[^\S\r\n]*$
和^Room Number\s?:\s?(.*?)[^\S\r\n]*$
const regex = /^Guest Name\s?:\s?(.*?)\s*\r?\nRoom Number\s?:\s?(.*)/m; const str = `The description value is Holrest Code: adip-345 Guest Name: Test_guest1613 Room Number: AK004 Request Number: 107157 Request Method: Email Dates Requested:25-Jul-2020 08:00PM If no specific date, weekday or weekend: N/A Start Time:25-Jul-2020 08:00PM Time Zone: ET `; let m = str.match(regex); console.log(m[1]); console.log(m[2]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.