正则表达式匹配向前或向后斜杠

时间:2016-02-01 16:56:55

标签: javascript regex

我有一个这样的字符串:

whatever/aaazzzzz

有时会出现这样的字符串:

whatever\bbbbzzzzz

我想在匹配/\

时拆分字符串

我试过的正则表达式似乎有用

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

当我在fiddle中使用它时,它适用于/,但不适用于\

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

使用此

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

import os
import xml.etree.ElementTree as etree
import subprocess

filename = "sample.xml"
__currentlocation__ = os.getcwd()
__fullpath__ = os.path.join(__currentlocation__,filename)
tree = etree.parse(__fullpath__)
root = tree.getroot()
hivetable = root.find("hivetable").text
dburl = root.find("dburl").text
username = root.find("username").text
password = root.find("password").text
tablename = root.find("tablename").text
mappers = root.find("mappers").text
targetdir = root.find("targetdir").text
print hivetable
print dburl
print username
print password
print tablename
print mappers
print targetdir

p = subprocess.call(['hadoop','fs','-rmr',targetdir],stdout = subprocess.PIPE, stderr = subprocess.PIPE)

答案 1 :(得分:1)

这里的问题不是正则表达式本身,而是JavaScript不会隐式支持字符串文字的不可避免的事实(即反斜杠被解释为打印而不是表示转义序列的那些。更多可以读取{{3} })。

默认情况下,从源代码其他派生的字符串被解释为文字,如here中所示。

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