簡體   English   中英

使用單詞分隔符拆分字符串

[英]Splitting a String using Word Delimiters

我有一個字符串如下

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和空格。 更新示例。

這將拆分為“和”或“或”,單詞周圍有任意數量的空格。

   String test = "2 < 3 and 3 > 2 or 4 < 6 and 7 < 8";

    String [] splitString = test.split("\\s*[and|or]+\\s*");
    for(int i = 0; i < splitString.length ; i ++){
        System.out.println(splitString[i]);
    }

output

2 < 3
3 > 2
4 < 6
7 < 8
String delim = " ";
String[] splitstrings = yourString.split(delim);
for (int i = 0; i < splitstrings.length(); i++) {
    splitstrings += delim;
}

當您遇到所有不同的空格排列以及語法增長時,您真正想要的是像JFlex這樣的工具。 從長遠來看,您將節省時間。

String str = "2 < 3 and 3 > 2 or 4 < 6 and 7 < 8";
System.out.println( ImmutableList.copyOf( str.split( "(?=and|or)" ) ) );

Output:

[2 < 3 , and 3 > 2 , or 4 < 6 , and 7 < 8]

據我所知,StringTokenizer 是唯一能夠返回使用的分隔符的 java 標准 class 。 剛剛從 OT 復制了正則表達式,假設它會做他想做的事(乍一看,我非常懷疑他的文字描述,但是哦,好吧 - 只需插入正確的)

    String input = "a > b and c < d or d > e and f > g";
    StringTokenizer tokenizer = new StringTokenizer(input, "\\sand\\s|\\sor\\s", true);
    while (tokenizer.hasMoreTokens()) {
        System.out.println(tokenizer.nextToken());
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM