Andy Zhang
Andy Zhang

Reputation: 43

javascript regular expression match special string

I have a string like this:


惊讶! 学会这些 625 单词就可以走遍天下!  
(Animal) ​动物​:  
Dog ​- 狗,     ​Cat ​- 猫,     ​Fish ​- 鱼,     ​Bird ​- 鸟,     ​Cow ​- 牛,     ​Pig ​- 猪,     ​Mouse ​- 老鼠, 
Horse ​- 马,     ​Wing ​- 翅膀,     ​Animal ​- 动物.  
(Transportation) ​交通​:  
Train ​- 火车,     ​Plane ​- 飞机,     ​Car ​- 汽车,     ​Truck ​- 卡车,     ​Bicycle ​- 自行车​
,  

I want to match Dog - 狗,Fish - 鱼 ... my regular expression is: const reg = /(.*)\s*-\s*(.*),/g, but the result is not what i expect.so how to write a correct one?

my final answer is [[Dog,狗],[Cat,猫],...],I know I should use regular expression, but it has trouble

Upvotes: 1

Views: 60

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

You can use

/(\S+)[\s\u200B]*-[\s\u200B]*([^,]*)/g

See the regex demo.

Details:

  • (\S+) - Group 1: one or more non-whitespace chars
  • [\s\u200B]* - zero or more whitespaces or ZWJ symbol
  • - - a hyphen
  • [\s\u200B]* - zero or more whitespaces or ZWJ symbol
  • ([^,]*) - Group 2: zero or more chars other than a comma.

Upvotes: 2

Related Questions