本文介绍了正则表达式问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我在Python中相当新,我还没有使用正则表达式

足以实现什么我想要。

我想在字符串中选择条款,这样我就可以在我的

数据库中进行搜索。


query =''"一些词语用和没有引号 ''

p = re.compile(magic_regular_expression)$< ---魔术发生了

m = p.match(查询)


我希望m.groups()返回:

(''有些单词'',''带'',''和'',''没有引号''' )


单个正则表达式是否可以实现,如果是这样,那将是什么




非常感谢任何帮助。


谢谢!!


Julien

解决方案


4月29日,8:46 * am,Julien< jpha ... @ gmail.comwrote:




Julien -


我花了几分钟时间试图找到你的解决方案, />
然后惩罚并使用pyparsing代替。 Pyparsing的运行速度会比re慢,但很多人发现使用可读的

类名和实例更容易,而不是重新编写类型:


来自pyparsing import OneOrMore,Word,printables,dblQuotedString,

removeQuotes


#当找到带引号的字符串时,删除引号,

#然后从内容中删除空格

dblQuotedString.setParseAction(removeQuotes,

lambda s:s [0] .strip() )


#define查询字符串中可以找到的术语

term = dblQuotedString | Word(printables)

query_terms = OneOrMore(term)


#解析查询字符串以提取术语

query =''" ;一些词语用和没有引号 ''

打印元组(query_terms.parseString(查询))


给:

(''some words'', ''with'',''和'',''没有引号'''

pyparsing wiki位于。你会发现

一个包含搜索查询解析器的示例页面,以及指向

a在线文档和演示文稿源的指示。


- Paul


Hi,

I''m fairly new in Python and I haven''t used the regular expressions
enough to be able to achieve what I want.
I''d like to select terms in a string, so I can then do a search in my
database.

query = '' " some words" with and "without quotes " ''
p = re.compile(magic_regular_expression) $ <--- the magic happens
m = p.match(query)

I''d like m.groups() to return:
(''some words'', ''with'', ''and'', ''without quotes'')

Is that achievable with a single regular expression, and if so, what
would it be?

Any help would be much appreciated.

Thanks!!

Julien

解决方案



Julien -

I dabbled with re''s for a few minutes trying to get your solution,
then punted and used pyparsing instead. Pyparsing will run slower
than re, but many people find it much easier to work with readable
class names and instances rather than re''s typoglyphics:

from pyparsing import OneOrMore, Word, printables, dblQuotedString,
removeQuotes

# when a quoted string is found, remove the quotes,
# then strip whitespace from the contents
dblQuotedString.setParseAction(removeQuotes,
lambda s:s[0].strip())

# define terms to be found in query string
term = dblQuotedString | Word(printables)
query_terms = OneOrMore(term)

# parse query string to extract terms
query = '' " some words" with and "without quotes " ''
print tuple(query_terms.parseString(query))

Gives:
(''some words'', ''with'', ''and'', ''without quotes'')

The pyparsing wiki is at http://pyparsing.wikispaces.com. You''ll find
an examples page that includes a search query parser, and pointers to
a number of online documentation and presentation sources.

-- Paul


这篇关于正则表达式问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 13:10