簡體   English   中英

使用正則表達式匹配字符串

[英]Match string using regex

我有以下變量:

var test = category~[330526|330519]^Size{1}~[m]

如何使用正則表達式匹配以獲得category~[330526|330519]

此值也可以更改,因此可能是category~[3303226|333219]

只需嘗試:

test.split('^')[0];
var test = 'category~[330526|330519]^Size{1}~[m]';

var result = test.split('^').shift();

小提琴

你可以;

 result = test.substr(0, test.indexOf("]") +1);

應該這樣做:

category~\[\d+\|\d+\]

如果您堅持使用正則表達式,那么這並不關心類別是(.*~\\[\\d+\\|\\d+\\]) 這是Rubular的證明 但是我不得不說,@ hsz的回答確實是最有見地的。 split可能是這項工作的正確工具。

還有另一種方法...

var test = 'category~[330526|330519]^Size{1}~[m]';

var result = test.replace(/\^.+/,"");

“ category〜[330526 | 330519] ^ Size {1}〜[m]”。replace(/(category〜[\\ d + \\ | \\\\ d +])。* /,“ $ 1”),應該獲取字符串,或者您也可以使用match。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM