使用单词分隔符分割字符串
我有一个字符串,
a > b and c < d or d > e and f > g
结果必须是:
a > b
and
c < d
or
d > e
and
f > g
我想在出现“and”、“or”时分割字符串,并检索分隔符以及标记。[我需要它们来评估表达式]
我尝试过使用 StringTokenizer
new StringTokenizer(x, "\\sand\\s|\\sor\\s", true);
但我没有得到想要的结果。 我尝试使用扫描仪,因为
Scanner sc = new Scanner(x);
sc.useDelimiter("and | or");
它可以分割但不返回分隔符。
请建议。
我上面已经给出了 a 、 b 、 c ,但是可能会有单词而不是带有空格的 a、b 、 c 。 更新了示例。
i have a string as below
a > b and c < d or d > e and f > g
outcome must be:
a > b
and
c < d
or
d > e
and
f > g
i want to split the string at occurrences of "and" , "or" and retrieve the delims as well along with the token.[i need them in order to evaluate the expression]
i tried using StringTokenizer as
new StringTokenizer(x, "\\sand\\s|\\sor\\s", true);
but i dont get desired outcome.
i tried using scanner as
Scanner sc = new Scanner(x);
sc.useDelimiter("and | or");
this is able to split but doesnt return the delimiters.
please suggest.
i have given a , b , c above but there cud be words instead of a,b , c with spaces.
Updated example.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这将在“and”或“or”上进行拆分,并在单词周围添加任意数量的空格。
输出
This will split on "and" or "or" with any number of spaces surrounding the words.
output
当您遇到所有不同的空格排列和语法时,您真正想要的是像 JFlex 这样的工具成长。从长远来看,您将节省时间。
What you really want is a tool like JFlex by the time you run into all the different permutations of white spaces and as your syntax grows. In the long run you will save time.
据我所知, StringTokenizer 是唯一能够返回所使用的分隔符的 java 标准类。只是从 OT 中复制了正则表达式,假设它会做他想要的事情(第二眼我对他的文字描述非常怀疑,但是哦,好吧 - 只需插入正确的一个)
A StringTokenizer is the only java standard class that is capable of returning the used delimiter as well as far as I'm aware. Just copied the regex from the OT assuming that it'll do what he wants (which on second glance I extremely doubt from his textual description, but oh well - just insert the right one)
输出:
Output: