java 使用单词作为分隔符分割字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12636417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:39:28  来源:igfitidea点击:

splitting a string using words as delimiters

javaregexstring

提问by Homie

I'm trying to take out special strings from a mother string using string.split in java with regular expressions.

我正在尝试使用带有正则表达式的 java 中的 string.split 从母字符串中取出特殊字符串。

string str = "name ching chang field computer engineering grade 9.98";
string[] splits = str.split("regex");

I want to use the words name, field and grade as delimiters. Now what should the regular expression be so that my string array (splits) has the following items in it:

我想使用名称、字段和等级作为分隔符。现在正则表达式应该是什么,以便我的字符串数组(拆分)中有以下项目:

splits[0] = "ching chang"  
splits[1] = "computer engineering"  
splits[2] = "9.98"  

回答by Grisha Weintraub

String str = "name ching chang field computer engineering grade 9.98";
String[] splits = str.split("name |field |grade ");

//test with
for(String s : splits)
    System.out.println(s);

回答by Nishant

    String str = "name ching chang field computer engineering grade 9.98";
    String[] splits = str.split("name|field|grade");
    System.out.println(Arrays.asList(splits));

回答by Adriaan Koster

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Fieldsplitter with configurable fields
 */
public class FieldSplitter {

    private static Logger LOG = new Logger();

    /**
     * Test method
     * 
     * @param args
     *            not used
     */
    public static final void main(String[] args) {

        String[] fields = new String[] { "name", "field", "grade" };
        // regular test case
        printFieldValues(fields,
                "name ching chang field computer engineering grade 9.98");
        // missing field
        printFieldValues(fields,
                "ching chang field computer engineering grade 9.98");
        // duplicate field
        printFieldValues(fields,
                "name ching chang field computer engineering name johnny bravo grade 9.98");
    }

    /**
     * Gets the values of the fields from the input. If a field is not found the
     * value is null. If a field occurs multiple times the last value is used.
     * 
     * @param fields
     *            the known fields
     * @param input
     *            the input containing consecutive fields and their values
     *            separated by whitespace
     * @return a Map containing all known fields and their values
     */
    public static Map<String, String> getFieldValues(String[] fields,
            String input) {
        Map<String, String> fieldValues = new HashMap<String, String>();
        for (String field : fields) {
            fieldValues.put(field, null);
        }
        String[] words = input.split("\s");
        LOG.debug("words:" + Arrays.toString(words));
        String field = null;
        int start = 0;
        for (String word : words) {
            if (fieldValues.containsKey(word)) {
                int end = input.indexOf(word, start);
                if (end < 0) {
                    throw new RuntimeException(String.format(
                            "Error: '%s' not found after position %s", word,
                            end));
                }
                if (field != null) {
                    fieldValues.put(field, input.substring(start, end));
                }
                field = word;
                start = end + word.length();
            }
        }
        if (field != null) {
            fieldValues.put(field, input.substring(start, input.length()));
        }
        return fieldValues;
    }

    private static void printFieldValues(String[] fields, String input) {
        for (Entry<String, String> field : getFieldValues(fields, input)
                .entrySet()) {
            LOG.debug(String.format("%s=%s", field.getKey(), field.getValue()));
        }
    }

    /** A simple logger */
    private static class Logger {
        void debug(String message) {
            System.out.println(message);
        }
    }
}

Output:

输出:

words:[name, ching, chang, field, computer, engineering, grade, 9.98]
grade= 9.98
name= ching chang 
field= computer engineering 
words:[ching, chang, field, computer, engineering, grade, 9.98]
grade= 9.98
name=null
field= computer engineering 
words:[name, ching, chang, field, computer, engineering, name, johnny, bravo, grade, 9.98]
grade= 9.98
name= johnny bravo 
field= computer engineering 

P.S. I just discovered a trivial but handy trick: In Eclipse select your code and press TAB to indent it. Then copy and paste the indented code into the Stackoverflow edit field. In this way the code will immediately render correctly.

PS 我刚刚发现了一个简单但方便的技巧:在 Eclipse 中选择您的代码并按 TAB 将其缩进。然后将缩进的代码复制并粘贴到 Stackoverflow 编辑字段中。通过这种方式,代码将立即正确呈现。