[英]How to split string by regular expression
我想通過正則表達式在字符“ @”和字符列表([,。!?{}})之間分割文本。 例如,我有下一個文本
@test,@ {@ test2,dasdas。 @ test3?} @ test4? @ test5!
我想得到下一個數組:
- 測試
- 測試2
- 測試3
- 測試4
- 測試5
我嘗試使用下一個正則表達式
/ @(。*?)[,{}!?。] /
但它返回不正確的數組。
有人可以幫我嗎?
您所需要做的就是匹配一個@
,然后使用\\w+
匹配並捕獲1個或多個字母數字符號:
@(\w+)
結果:
test
test2
test3
test4
test5
在Java中,您可以簡單地匹配子字符串:
String s = "@test, @{@test2, dasdas. @test3?} @test4? @test5!";
Pattern pattern = Pattern.compile("@(\\w+)");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
System.out.println(matcher.group(1));
}
如果是JavaScript,則可以執行以下操作。
string1 =“ @test,@ {@ test2,dasdas。@ test3?} @ test4?@ test5!”;
array1 = string1.split(“ @”); / *數組[“,” test,“,” {“,” test2,dasdas。“,” test3?}“,” test4?“,” test5!“ ] * /
您可以在Javascript中使用以下內容:
var re = /@([^,.!?{}@]+)/g;
var str = '@test, @{@test2, dasdas. @test3?} @test4? @test5!';
var m;
var arr;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex)
re.lastIndex++;
arr.push(m[1]);
}
console.log(arr);
//=> ["test", "test2", "test3", "test4", "test5"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.