V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
starvedcat
V2EX  ›  问与答

正则表达式问题

  •  
  •   starvedcat · 2016-11-27 14:59:12 +08:00 · 1053 次点击
    这是一个创建于 2731 天前的主题,其中的信息可能已经有所发展或是发生改变。

    现有字符串:

    people(aa, bb) VALUES (1, 2)
    (注意, people 后面没有空格, VALUES 后面有一个空格)
    

    我需要把它分割成:

    people
    (aa
    bb)
    VALUES
    (1
    2)
    

    语言是 Java

    我不太会的点在于:我希望把空格和逗号吃掉,但是保留括号

    我现在的进展:

    public class T {
    	public static void main(String[] args) {
    		String str = "people(aa, bb) VALUES (1, 2)";
    		String parts[] = str.split(",| |(?=[\\(])");
    
    		for (String part : parts) {
    			System.out.println(part);
    		}
    	}
    }
    

    应该怎么写呢?

    第 1 条附言  ·  2016-11-27 15:50:34 +08:00

    这次应该真的解决了,用这个

    (,| |(?=.)(?=\\())
    
    8 条回复    2016-11-27 15:07:32 +08:00
    starvedcat
        1
    starvedcat  
    OP
       2016-11-27 15:00:11 +08:00
    (?=regex)这个用法我是看 http://www.regular-expressions.info/refadv.html 这里的……
    starvedcat
        2
    starvedcat  
    OP
       2016-11-27 15:01:23 +08:00
    连续的空格最多一个(之前有其他的处理)
    starvedcat
        3
    starvedcat  
    OP
       2016-11-27 15:03:51 +08:00
    已解决,用",| |(=[\\(])"就行……现在理解那个用法
    starvedcat
        4
    starvedcat  
    OP
       2016-11-27 15:04:23 +08:00
    真是打搅了,管理员在的话麻烦人工下沉。。。
    rrfeng
        5
    rrfeng  
       2016-11-27 15:06:35 +08:00
    split 只能根据『某个字符』切割,没法根据『某个位置』切割。虽然 regex 里有表示『某个位置』的语法。
    所以一次应该是不行的,可以考虑加一次替换。
    rrfeng
        6
    rrfeng  
       2016-11-27 15:07:13 +08:00
    @starvedcat 看来我肤浅了。。。。
    starvedcat
        7
    starvedcat  
    OP
       2016-11-27 15:07:16 +08:00
    等等,搞错了,还是没解决= = 继续。。。
    starvedcat
        8
    starvedcat  
    OP
       2016-11-27 15:07:32 +08:00
    @rrfeng 我脑残了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   976 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 21:30 · PVG 05:30 · LAX 14:30 · JFK 17:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.