0
votes

I want to split text by regex between character "@" and list of characters ([,.!?{} ]). Example, i have the next text

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

and i want to get the next array:

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

I try to use the next regular expression

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

but it return incorrect array.
Could someone help me?

3
Try regex101.com or a similar tool, these are very helpful when debugging regex. - Ian
Please post the code. Is it JS? - Wiktor Stribiżew
No, it is Java with string split method - Dmitry Igumnov

3 Answers

2
votes

All you need is to match a @ and then match and capture 1 or more alphanumeric symbols with \w+:

@(\w+)

See regex demo

Results:

test
test2
test3
test4
test5

In Java, you can simply match the substrings:

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).

0
votes

If it is JavaScript, the following works.

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

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

0
votes

You can use something like this in 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