简体   繁体   English

正则表达式以匹配正斜杠或反斜杠

[英]Regex to match forward or backward slash

I have a string like this : 我有一个像这样的字符串:

whatever/aaazzzzz

and sometimes a string like that : 有时像这样的字符串:

whatever\bbbbzzzzz

I would like to split the string when I match / or \\ 我想在匹配/\\时拆分字符串

The regex I tried seems to work 我尝试过的正则表达式似乎有效

https://regex101.com/r/gP5gL0/1 https://regex101.com/r/gP5gL0/1

When I use it in the fiddle , it works with / but not with \\ 当我在小提琴中使用它时,它可与/但不适用于\\

Any ideas? 有任何想法吗?

Use this 用这个

var arr = str.split(/[\\|\/]/);

 var str = 'whatever\\\\bbbbzzzzz'; alert(str.split(/[\\\\|\\/]/)) 

The issue here is not the regex itself, but the unavoidable fact that JavaScript doesn't implicitly support string literals (ie ones where backslashes are interpreted as printed as opposed to denoting an escape sequence. Much more can read here ). 这里的问题不是regex本身,而是不可避免的事实,即JavaScript不隐式支持字符串文字(即,反斜杠被解释为打印而不是表示转义序列的字符串。 在此处可以读到更多内容)。

Strings derived from any source other than source code are interpreted as literal by default, as demonstrated in this fiddle . 该小提琴所示 ,默认情况下,从源代码以外的任何其他源派生的字符串都被解释为文字。

<script>
function splitTheString()
{
  //test = escape("whatever\aaaaaa");
  var test = document.getElementById("strToSplit").value;
  a = test.split(/(\\|\/)/)[0];
  alert(a);
}
</script>
<form>
Split this string:<br>
  <input type="text" id="strToSplit">
  <a href="javascript:splitTheString();">Split the string</a>
</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM