简体   繁体   English

如何通过正则表达式拆分字符串

[英]How to split string by regular expression

I want to split text by regex between character "@" and list of characters ([,.!?{} ]). 我想通过正则表达式在字符“ @”和字符列表([,。!?{}})之间分割文本。 Example, i have the next text 例如,我有下一个文本

@test, @{@test2, dasdas. @test,@ {@ test2,dasdas。 @test3?} @test4? @ test3?} @ test4? @test5! @ test5!

and i want to get the next array: 我想得到下一个数组:

  1. test 测试
  2. test2 测试2
  3. test3 测试3
  4. test4 测试4
  5. test5 测试5

I try to use the next regular expression 我尝试使用下一个正则表达式

/@(.*?)[,{} !?.]/ / @(。*?)[,{}!?。] /

but it return incorrect array. 但它返回不正确的数组。
Could someone help me? 有人可以帮我吗?

All you need is to match a @ and then match and capture 1 or more alphanumeric symbols with \\w+ : 您所需要做的就是匹配一个@ ,然后使用\\w+匹配并捕获1个或多个字母数字符号:

@(\w+)

See regex demo 正则表达式演示

Results: 结果:

test
test2
test3
test4
test5

In Java, you can simply match the substrings: 在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)); 
}

See IDEONE demo (or another demo with the results stored in an array). 请参阅IDEONE演示 (或另一个将结果存储在数组中的演示 )。

If it is JavaScript, the following works. 如果是JavaScript,则可以执行以下操作。

string1 = "@test, @{@test2, dasdas. @test3?} @test4? @test5!"; string1 =“ @test,@ {@ test2,dasdas。@ test3?} @ test4?@ test5!”;

array1 = string1.split("@"); array1 = string1.split(“ @”); /* Array [ "", "test, ", "{", "test2, dasdas. ", "test3?} ", "test4? ", "test5!" / *数组[“,” test,“,” {“,” test2,dasdas。“,” test3?}“,” test4?“,” test5!“ ] */ ] * /

You can use something like this in Javascript: 您可以在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"]

RegEx Demo 正则演示

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

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