最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

C# Regex.Split is working differently than JavaScript - Stack Overflow

programmeradmin2浏览0评论

I'm trying to convert this long JS regex to C#.

The JS code below gives 29 items in an array starting from ["","常","","に","","最新","、","最高"...]

var keywords = /(\ |[a-zA-Z0-9]+\.[a-z]{2,}|[一-龠々〆ヵヶゝ]+|[ぁ-んゝ]+|[ァ-ヴー]+|[a-zA-Z0-9]+|[a-zA-Z0-9]+)/g;
var source = '常に最新、最高のモバイル。Androidを開発した同じチームから。';
var result = source.split(keywords);

But the C# code below gives a non-splitted single item in string[].

var keywords = @"/(\ |[a-zA-Z0-9]+\.[a-z]{2,}|[一-龠々〆ヵヶゝ]+|[ぁ-んゝ]+|[ァ-ヴー]+|[a-zA-Z0-9]+|[a-zA-Z0-9]+)/g";
var source = @"常に最新、最高のモバイル。Androidを開発した同じチームから。";
var result = Regex.Split(source, keywords);

Many questions in Stack Overflow are covering relatively simple expressions only, so I cannot find my mistakes.

What am I missing?

I'm trying to convert this long JS regex to C#.

The JS code below gives 29 items in an array starting from ["","常","","に","","最新","、","最高"...]

var keywords = /(\ |[a-zA-Z0-9]+\.[a-z]{2,}|[一-龠々〆ヵヶゝ]+|[ぁ-んゝ]+|[ァ-ヴー]+|[a-zA-Z0-9]+|[a-zA-Z0-9]+)/g;
var source = '常に最新、最高のモバイル。Androidを開発した同じチームから。';
var result = source.split(keywords);

But the C# code below gives a non-splitted single item in string[].

var keywords = @"/(\ |[a-zA-Z0-9]+\.[a-z]{2,}|[一-龠々〆ヵヶゝ]+|[ぁ-んゝ]+|[ァ-ヴー]+|[a-zA-Z0-9]+|[a-zA-Z0-9]+)/g";
var source = @"常に最新、最高のモバイル。Androidを開発した同じチームから。";
var result = Regex.Split(source, keywords);

Many questions in Stack Overflow are covering relatively simple expressions only, so I cannot find my mistakes.

What am I missing?

Share Improve this question edited Sep 4, 2018 at 8:01 Pang 10.1k146 gold badges86 silver badges124 bronze badges asked Sep 4, 2018 at 1:58 YoungjaeYoungjae 25.1k19 gold badges117 silver badges203 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 15

Your RegEx is wrong, you should not start and end with '/' or '/g' You specify a string in the constructor, not a JavaScript Regex (with '/ /' syntax.). That's a Javascript syntax.

Actually the same applies to JavaScript when you use a string constructor like this:

var regex = new RegExp('//'); // This will match 2 slashes

Here is a C# example code

string keywords = @"(\ |[a-zA-Z0-9]+\.[a-z]{2,}|[一-龠々〆ヵヶゝ]+|[ぁ-んゝ]+|[ァ-ヴー]+|[a-zA-Z0-9]+|[a-zA-Z0-9]+)";
string source = @"常に最新、最高のモバイル。Androidを開発した同じチームから。";
string [] res = Regex.Split(source, keywords);

string single = "";
foreach ( string str in res )
    single += "'" + str + "',";
Console.WriteLine("{0}", single);
发布评论

评论列表(0)

  1. 暂无评论