从Java中的字符串中重写单词,数字和引号

时间:2012-05-31 18:58:05

标签: java regex string words

我在Java中有一个关于Regex的快速问题(尽管其他语言可能类似)。

我要做的是转换像这样的字符串:

 How are you "Doing well" How well 10 "That's great"

//# I want the Regex in Java to match out all of the words, numbers, 
//# and things inside quotation marks. Ideally, I'd get something like this 

How
Are
You
"Doing Well"
How 
Well
10
"That's Great!"

我试图使用的正则表达式如下:

String RegexPattern =   "[^"+           //  START_OR: start of line OR" 
                        "\\s" +         //  empty space OR
                        "(\\s*?<=\")]" + // ENDOR: preceeded by 0 or more spaces and a quotation mark 
                        "(\\w+)" +      // the actual word or number
                        "[\\s" +        // START_OR: followed by a space OR
                        "(?=\")" +      // followed by a quotation mark OR
                        "$]";           // ENDOF:  end of line

但这对我不起作用;即使是更简单的字符串!我花了很多时间在这里寻找类似的问题。如果我不需要报价,我可以使用拆分;但最终,这种模式会变得复杂得多,所以我需要使用正则表达式(这只是第一次迭代)。

我很感激任何帮助;提前致谢!

3 个答案:

答案 0 :(得分:2)

我认为[ ]并不意味着你的意思。在方括号内,^实际上是字符类的否定运算符。在开始此任务之前,您应该使用较小的正则表达式练习。您正在寻找的模式更像是:

    \s*([^"\s]+|"[^"]*")

您可以在此处查看此操作:http://rubular.com/r/enq7eXg9Zm

如果你不想要单词中的符号,那么最好使用第二个删除它们的正则表达式,例如。

    \W

答案 1 :(得分:0)

你可以分多步完成(python中的代码,但逻辑和模式应该相同)

1 - 获取双引号内的所有字符串:

r = re.findall(r'\"([^"]*)\"','How are you "Doing well" How well 10 "That\'s great"')

结果:['Doing well', "That's great"]

2 - 从文本中删除这些字符串:

r = re.sub(r'\"([^"]*)\"', "", 'How are you "Doing well" How well 10 "That\'s great"')

结果:'How are you How well 10 '

3 - 现在你可以进行拆分加上步骤1中的双引号。

最终不是一个好/干净的解决方案,但它应该有用。

答案 2 :(得分:0)

这对你有用。 (\ “[^ \”] + \“)|([^ \ S] +)

相关问题