开发者

Processing my own escape characters using Regular expression

First of all I have to apologize for my poor English, Please let me explain my case, Assume that I have 2 text boxes for a user to input. On the server side, I want to combine the two strings as a single string delimited by ',' character. For example, If a user inputs the first text box as "hello world" and the second text box "foo bar", the final string should be "hello world,foo bar". This string needs to be split later on for other operations to utilize its content. So when the string is split, as the ',' character is used as a delimitor, the result string will be string[0] = "hello world" string[1] = "foo bar" respectively.

Of course this is vulnerable when a user types ',' character in their string, resulting in a string that cannot be split correctly. For example, when the user enters "hello,world" in the first text box and "foo,bar" in the second text box, the final string would be "hello,world,foo,bar" and the split result would wrongly be 4 separate strings.

I came up with an idea of custom escape characters.That is if a user inputs ',' character, it must be prepended with '/' character on the server side. For example, If a user inputs "hello,world" and "foo,bar" , the final string will be "hello/,world,foo/,bar" which can now be split because the exact delimitor is known which is a single ',' character without '/' character prepending it.

I wrote some java code to process it as follows:

    String testText = "hello/,world,foo/,bar";
    String[] split = testText.split("[^/],");
    for(int i=0; i<split.length; i++)
    {
        System.out.println(split[i]);
    }

The returned result is

string[0] = hello/,worl

开发者_如何学编程

string[1] = foo/,bar

which is incorrect because the 'd' character of the word "world" is lost. It seems that the delimiter for this case is some character which is not / followed by ',' which is quite understandable. But I want something like "split the string with the delimiter ',' which only follows the character that is not '/' character. So apply to my case, only ',' character in the middle of the string will be split so the final result will be correct as follows:

string[0] = hello/,world

string[1] = foo/,bar

I realize that I may have to rewrite my regular expression but I don't know how. Any suggestion would be welcome.


Use a negative look behind

testText.split("(?<!/),");

The neagative lookbehind ensures that there is no / before the , without matching it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜