正则表达式从String获取特定值

时间:2018-05-22 18:53:11

标签: java regex

我试图从带有正则表达式的段落中获取值。我尝试使用正则表达式:

String regex =  "Are you a seller/buyer, a manufacturer, or both for the products you want to list?
ANSWER(S): s*([^,]+)"

段落将永远是这个子字符串您是否是您要列出的产品的卖家/买家,制造商或两者? ANSWER(S): <interested field>。我希望在给定段落的这个问题中获得:之后的值。

:之后的字符串可以是= Both,Seller,Buyer或Manufacturer

之一

有人可以告诉我我做错了什么吗?

:出现在给定段落的许多地方,字符串Are you a seller/buyer, a manufacturer, or both for the products you want to list? ANSWER(S)将被修复。

1 个答案:

答案 0 :(得分:2)

因此,如果您只想匹配BothSellerBuyerManufacturer,则可以使用以下正则表达式:

/Are you a seller\/buyer, a manufacturer, or both for the products you want to list\? ANSWER\(S\): (Both|Seller|Buyer|Manufacturer)/

以下是一个示例用法:

const re = /Are you a seller\/buyer, a manufacturer, or both for the products you want to list\? ANSWER\(S\): (Both|Seller|Buyer|Manufacturer)/;

let test = "lorem ipsum dolor sit amet Are you a seller/buyer, a manufacturer, or both for the products you want to list? ANSWER(S): Both lorem ipsum dolor sit amet";

console.log("The anser is: " + re.exec(test)[1]  );