简体   繁体   English

使用正则表达式捕获文本

[英]Capture the text using regex

I have a text where I need to capture the second group我有一个文本需要捕获第二组

Response on your Property Listing 
Dear Rahul Bond, 
A user is interested in your Property, ID 62455995: 2 BHK , Multistorey 
Apartment in Raheja Vihar , Mumbai. 
Details of Contact Made: 
Sender's Name: Test (Individual) 

The text to be retrieved is 2 BHK, Multistorey Apartment in Raheja Vihar, Mumbai.要检索的文本是2 BHK, Multistorey Apartment in Raheja Vihar, Mumbai。 This does start with **A user is interested in your Property, ID xxxxxxx: **这确实以 **A 用户对您的属性感兴趣,ID xxxxxxx 开头:**

A user is interested in your Property, ID 62455995: 2 BHK , Multistorey 
    Apartment in Raheja Vihar , Mumbai. 

The expected output is 2 BHK, Multistorey Apartment in Raheja Vihar, Mumbai.预期的 output 是2 BHK,位于孟买 Raheja Vihar 的多层公寓。

I have tried with .match(/(A user is interested in your Property, ID.*[^:]) (.*\n.*)/g) Unfortunetly it gives me all 2 lined text.我试过.match(/(A user is interested in your Property, ID.*[^:]) (.*\n.*)/g)不幸的是,它给了我所有 2 行文本。

You can use this regex:您可以使用此正则表达式:

 const text = `Response on your Property Listing Dear Rahul Bond, A user is interested in your Property, ID 62455995: 2 BHK, Multistorey Apartment in Raheja Vihar, Mumbai. Details of Contact Made: Sender's Name: Test (Individual)`; const rgx = /(?<=A user is interested in your Property, ID \d+: )(.*\n.*)/g; const result = text.match(rgx); console.log(result);

It works here https://regexr.com/6tulh它在这里工作https://regexr.com/6tulh

From the above comment...从上面的评论...

"How about more generically looking for... ID , followed by a whitespace (sequence), followed by a sequence of 8 digits, followed by a single colon, followed by another whitespace (sequence) and then capturing anything which is not a dot/period including the first occurring dot/period... /ID\s+\d{8}\:\s+(?<description>[^.]+\.)/g " “如何更一般地寻找... ID ,后跟一个空格(序列),后跟一个 8 位数字序列,后跟一个冒号,然后是另一个空格(序列),然后捕获任何不是点的东西/句点包括第一个出现的点/句点... /ID\s+\d{8}\:\s+(?<description>[^.]+\.)/g "

... and making use of the proposed regex... ...并利用建议的正则表达式...

 const multilineText = `Response on your Property Listing Dear Rahul Bond, A user is interested in your Property, ID 62455995: 2 BHK, Multistorey Apartment in Raheja Vihar, Mumbai. Details of Contact Made: Sender's Name: Test (Individual)`; // see... [https://regex101.com/r/uDFHaV/1] const regX = /ID\s+\d{8}\:\s+(?<description>[^.]+\.)/g; // either... console.log( [...multilineText.matchAll(regX)].map(({ groups: { description } }) => description) ); // or... console.log( [...multilineText.matchAll(regX)] [0]?.groups.description ); //... or... console.log( regX.exec(multilineText)?.groups.description );
 .as-console-wrapper { min-height: 100%;important: top; 0; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM