简体   繁体   中英

How to escape delimiter while tokenizing string in java

I have a regex pattern like "(\\\\d{4},\\\\d{2},\\\\d{2} :\\\\d{2}:\\\\d{2}:\\\\d{2})" I am passing this pattern as argument to a function which tokenizes the input string based on "," .

Example:

func((\\d{4},\\d{2},\\d{2} :\\d{2}:\\d{2}:\\d{2}),func(n))";

How do I escape the comma in the regex while tokenizing?

Can you please post the function which tokenizes the string? Could help with respect to your code then.

With no such information, you could use split() as follows(if all you want to do is split on ","):

String s = "Messages,Hello\,World,Hobbies,Java\,Programming";
System.out.println(Arrays.toString(s.split("(?<!\\\\),")));

Refer - http://www.javacreed.com/how-to-split-a-string-with-escaped-delimiters/

You could replace your code with:

String str = "(\\d{4}\\,\\d{2}\\,\\d{2} \\d{2}:\\d{2}:\\d{2}), func(a)";
String[] tokens = str.split("(?<!\\\\),");
System.out.println(Arrays.toString(tokens));

This will give you a string array of tokens split on ","

The @Derryl Thomas answer is probably the correct answer. Here is an alternate technique.

  1. Use something else to indicate the comma in your regex.
  2. Split based on commas.
  3. Change the "something else" back to a comma.

For example:

  1. Instead of "(\\\\d{4},\\\\d{2},\\\\d{2} :\\\\d{2}:\\\\d{2}:\\\\d{2})"
    Use "(\\\\d{4}boppity\\\\d{2}boppity\\\\d{2} :\\\\d{2}:\\\\d{2}:\\\\d{2})"
  2. Do the split based on comma.
  3. Change the "boppity" in the regex to a ","; perhaps like this:
    newStringVariable = yourStringVariable.replace("boppity", ",")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM