用于去除术语的Python正则表达式

时间:2018-10-02 11:44:19

标签: python

我想用这些规则去除术语: 从左去除所有字符,字母数字字符除外 从右去除所有字符,除了撇号和字母数字字符 我使用了linecache = readercache.readLine(); System.out.println(linecache); String pattern = "(\\d+(?=%))"; // just include () Pattern patterncf1 = Pattern.compile(pattern) Matcher matchercf1 = patterncf1.matcher(linecache); String passedvalue = matchercf1.group(1); System.out.println(passedvalue); str.lstrip函数:

str.rstrip

我认为可以使用正则表达式在一行中完成此操作。我该怎么办

1 个答案:

答案 0 :(得分:0)

尝试一下:

  

通过Python定义'\ W == [^ a-zA-Z0-9_],其中排除了所有数字,   字母和_

>>> import re, string
>>> pattern = re.compile('[\W_]+')
>>> stringe1="    hi bye hithisitstesing 8909 okay left "
>>> pattern.sub('', stringe1.lstrip())
'hibyehithisitstesing8909okayleft'

另一个例子:

>>> import re
>>> string = "Kl13@£$%[};'\""
>>> pattern = re.compile('\W')
>>> string = re.sub(pattern, '', string)
>>> print string
Kl13
相关问题