从正则表达式中排除括号中的字符串? [英] Exclude strings within parentheses from a regular expression?

查看:98
本文介绍了从正则表达式中排除括号中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找将以空格分隔的字符串拆分为一系列搜索字词的方法.但是,这样做时,我想忽略括号内的空格.例如,我希望能够分割字符串

I'm looking to split space-delimited strings into a series of search terms. However, in doing so I'd like to ignore spaces within parentheses. For example, I'd like to be able to split the string

a, b, c, search:(1, 2, 3), d

进入

[[a] [b] [c] [search:(1, 2, 3)] [d]]

有人知道如何使用Java中的正则表达式来做到这一点吗?

Does anyone know how to do this using regular expressions in Java?

谢谢!

推荐答案

这不是完整的正则表达式,但可以帮助您:

This isn't a full regex, but it'll get you there:

(\([^)]*\)|\S)*

这是一个常见的技巧,将一个长字符串当作一个字符来对待.在右侧,我们将非空格字符与 \ S 匹配.在左侧,我们将一组平衡的括号匹配,中间包含任何括号.

This uses a common trick, treating one long string of characters as if it were a single character. On the right side we match non-whitespace characters with \S. On the left side we match a balanced set of parentheses with anything in between.

最终结果是将一组平衡的括号视为单个字符,因此正则表达式作为一个整体与单个单词匹配,其中一个单词可以包含这些带有括号的组.

The end result is that a balanced set of parentheses is treated as if it were a single character, and so the regex as a whole matches a single word, where a word can contain these parenthesized groups.

(请注意,由于这是一个正则表达式,因此无法处理嵌套括号.一组括号是限制.)

(Note that because this is a regular expression it can't handle nested parentheses. One set of parentheses is the limit.)

这篇关于从正则表达式中排除括号中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆