简体   繁体   English

如何在Java中标记字符串时转义定界符

[英]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 "," . 我有一个正则表达式模式,例如"(\\\\d{4},\\\\d{2},\\\\d{2} :\\\\d{2}:\\\\d{2}:\\\\d{2})"我正在将此模式作为参数传递给一个函数,该函数基于","标记输入字符串。

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 ","): 如果没有此类信息,则可以按如下方式使用split()(如果要执行的所有操作都在“,”上拆分):

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/ 请参阅-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. @Derryl Thomas答案可能是正确的答案。 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})" 代替"(\\\\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})" 使用"(\\\\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 ","; 将正则表达式中的“ boppity”更改为“,”; perhaps like this: 也许像这样:
    newStringVariable = yourStringVariable.replace("boppity", ",")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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