C# Regex.Split is working differently than JavaScript

C# Regex.Split is working differently than JavaScript



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.


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?




2 Answers
2



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.


'/'


'/g'



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



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


var regex = new RegExp('//');





Thanks, I removed first / and last /g then it works.
– Youngjae
Sep 4 at 2:20


/


/g



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



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Some of your past answers have not been well-received, and you're in danger of being blocked from answering.



Please pay close attention to the following guidance:



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)