[英]regex between two special characters
有沒有辦法在 JQuery 或 Javascript 中復制這個 PHP 片段...
<?php
$A = preg_match_all('#{.*(.*)}#U', $value, $B); //matches all between {} put it into array "B"
$C = $B[1]; // array[0] = "{content}" --- array[1] = "content"
?>
我一直試圖找到類似的東西大約 4 個小時,但無濟於事。 目標基本上是找到{
和}
之間的所有內容,然后提取出有用的信息。
我不是 Javascript 專家,所以我很感激任何幫助。 先感謝您。
您可以將 { 和 } 之間的所有文本塊放入一個數組中:
function getBracedText(input) {
var re = /\{(.*?)\}/g, matches, output = [];
while (matches = re.exec(input)) {
output.push(matches[1]);
}
return(output);
}
var str = "Some text {tag} and more {text}";
var results = getBracedText(str);
// results == ["tag", "text"];
工作演示: http : //jsfiddle.net/jfriend00/DT4Km/
正則表達式在所有語言中幾乎相同。 如果您想獲取{}
之間的所有內容並將其放入數組中,您可以這樣做:
var arr = [];
var str = 'Lorem {ipsum dolor} sit {amet} conseteur {adipisci}';
str.replace(/{(.+?)}/g, function(a, b){ arr.push(b) });
console.log(arr); //=> ["ipsum dolor", "amet", "adipisci"]
這個表達式應該可以正常工作:
/{([^}]+)}/g
這樣的事情應該做:
var re = /{[^}]*}/g;
var s = '{foo},bar,{fum}';
alert(s.match(re)); // ['{foo}','{fum}']
但您可能不希望包含“{}”。
var re = /{([^}]*)}/g;
var s = '{foo},bar,{fum}';
var a = [];
var b;
while (b = re.exec(s)) {
a.push(b[1]);
}
alert(a); // ['foo','fum'];
肯定有一種方法可以使用單個正則表達式並且沒有循環來做到這一點。
這是你需要的嗎?
var value = "some {example}";
value.match(/{([^}]+)}/); //array[0] = "{example}" --- array[1] = "example"
var str = '{Some groovy text}not so groovy text';
var regex = /\{(.*?)\}/;
var value = str.match(regex)[1]; // 'Some groovy text';
這將檢索括號內的內容。 希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.