Java使用正则表达式拆分带有双引号内内容的字符串。

huangapple go评论76阅读模式
英文:

Java split string with regex, anything inside Double Quotes

问题

我正在尝试分割一个字符串,类似于 String s = "do not split this \"split this\"";

String[] split = s.split("(?<=\\s)| (?=\") | ((?=[^A-Za-z0-9])|(?<=[^A-Za-z0-9]));

将会得到 ["do", " ", "not", " ", "split", "this", " ", "split this"];

我想保留所有单词、空白,但忽略双引号内的任何内容~

英文:

I am trying to split a string such as String s = "do not split this \"split this\"";

String[] split = s.split("(?<=\\s)| (?=\") | ((?=[^A-Za-z0-9])|(?<=[^A-Za-z0-9]));

will give me ["do", " ", "not", " ", "split", "this", " ", "split this"];

I would like to keep all words, white spaces as well, but ignore anything inside double quotes~

答案1

得分: 1

*just a guess:*

    String s = "do not split this \"split this\"";
    String[] split = s.split("(?<!\".{0,255}) | (?!.*\".*)");  // do, not, split, this, "split this";

*don't split at the blank, if the blank is surrounded by quotes*<br />
split at the blank when the 255 characters to the left *and* all characters to the right of the blank are no quotes
英文:

just a guess:

String s = &quot;do not split this \&quot;split this\&quot;&quot;;
String[] split = s.split( &quot;(?&lt;!\&quot;.{0,255}) | (?!.*\&quot;.*)&quot; );  // do, not, split, this, &quot;split this&quot;

don't split at the blank, if the blank is surrounded by quotes<br />
split at the blank when the 255 characters to the left and all characters to the right of the blank are no quotes

huangapple
  • 本文由 发表于 2020年4月8日 23:21:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/61104216.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定