Home > Back-end >  javascript regular expression match special string
javascript regular expression match special string

Time:01-17

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

CodePudding user response:

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.
  • Related