Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从字符串中提取变量值_Java_Regex_String - Fatal编程技术网

Java 从字符串中提取变量值

Java 从字符串中提取变量值,java,regex,string,Java,Regex,String,鉴于用户只能以特定格式输入值,我需要将该字符串的相关部分提取到Java变量中 例如,可以接受的格式有:- String types[] = {"The quick brown ${animal} jumped over the lazy ${target}.", "${target} loves ${animal}.", "${animal} became friends with ${target}"}; 变量:- pr

鉴于用户只能以特定格式输入值,我需要将该字符串的相关部分提取到Java变量中

例如,可以接受的格式有:-

String types[] = {"The quick brown ${animal} jumped over the lazy ${target}.",
                  "${target} loves ${animal}.",
                  "${animal} became friends with ${target}"};
变量:-

private String animal;
private String target;
现在,如果用户输入快速棕色狐狸跳过懒惰的狗,则动物变量应设置为fox,目标变量应设置为dog

如果用户输入与任何给定类型都不匹配,则应显示错误

基本上,我正试图做org.apache.commons.lang.text.StrSubstitutor所做的相反的事情

我的方法看起来效率低下,因此请求帮助:-


创建正则表达式模式,找出输入字符串的类型,然后为每个类型编写不同的逻辑。例如,对于第一种类型,在单词brown之后获取单词并将其分配给variable animal,依此类推。

您可以使用命名的捕获组执行此操作:

String userInput = "dog loves fox.";

String types[] = {"The quick brown (?<animal>.*?) jumped over the lazy (?<target>.*?).",
                  "(?<target>.*?) loves (?<animal>.*?).",
                  "(?<animal>.*?) became friends with (?<target>.*?)"};

Matcher m;

for(int i=0; i<types.length(); i++;){
    if(userInput.matches(types[i]){
        m = Pattern.compile(types[i]).matcher(userInput);
        break;
    }
}

m.find();

String animal = m.group("animal");
String target = m.group("target");
使用@Josh Withee的:-

测试:-

    @Test
    public void shouldExtractVariablesFromString() {
        String input = "The quick brown fox jumped over the lazy dog.";
        String types[] = {"The quick brown (?<animal>.*) jumped over the lazy (?<target>.*).",
                "(?<target>.*) loves (?<animal>.*).",
                "(?<animal>.*) became friends with (?<target>.*)"};
        Map<String, String> resultMap = StringUtils.extractVariablesFromString(input, Arrays.asList(types), "animal", "target1", "target");
        Assert.assertEquals("fox", resultMap.get("animal"));
        Assert.assertEquals("dog", resultMap.get("target"));
        Assert.assertFalse(resultMap.containsKey("target1"));
    }

    @Test
    public void shouldReturnEmptyMapIfInputDoesntMatchAnyPatternForVariableExtraction() {
        String input = "The brown fox passed under the lazy dog.";
        String types[] = {"The quick brown (?<animal>.*) jumped over the lazy (?<target>.*).",
                "(?<animal>.*) became friends with (?<target>.*)"};
        Map<String, String> resultMap = StringUtils.extractVariablesFromString(input, Arrays.asList(types), "animal", "target1", "target");
        Assert.assertTrue(resultMap.isEmpty());
    }

在一个罕见的例子中,我实际上发现了一篇与您的问题完全相同的Code Ranch文章:只需根据您的问题调整代码样本。@TimBiegeleisen这是一个不同的问题,我不认为简单地使用appendReplacement就可以解决它,appendReplacement提供字符串的匹配部分。Map valuesMap=new HashMap;动物,敏捷的棕色狐狸;valuesMap.puttarget,懒狗;String templateString=${animal}跳过了${target}。;StrSubstitutor sub=新的StrSubstitutorvaluesMap;String resolvedString=sub.replacetemplateString;谢谢马拉松55。我必须搬走吗?从命名组的末尾开始使其工作。比如?*?已更改为?*。我添加了一个答案,试图将其转换为Java8。还有,有没有什么方法可以让我不必提供动物和目标这样的名称,而仍然可以得到一张地图,上面有它找到的所有命名组?i、 在我的回答中,我不想在参数中提供variableNames。你可以随意命名命名的捕获组。很明显,它们不必与变量同名。我的意思是,与在m.groupanimal中按名称请求组不同,有没有一种方法可以不指定组的名称并获取所有组?类似于m.getAllGroups,它将返回一个映射,其中组名作为键,实际值作为映射值?如果没有办法,这也行。谢谢
    @Test
    public void shouldExtractVariablesFromString() {
        String input = "The quick brown fox jumped over the lazy dog.";
        String types[] = {"The quick brown (?<animal>.*) jumped over the lazy (?<target>.*).",
                "(?<target>.*) loves (?<animal>.*).",
                "(?<animal>.*) became friends with (?<target>.*)"};
        Map<String, String> resultMap = StringUtils.extractVariablesFromString(input, Arrays.asList(types), "animal", "target1", "target");
        Assert.assertEquals("fox", resultMap.get("animal"));
        Assert.assertEquals("dog", resultMap.get("target"));
        Assert.assertFalse(resultMap.containsKey("target1"));
    }

    @Test
    public void shouldReturnEmptyMapIfInputDoesntMatchAnyPatternForVariableExtraction() {
        String input = "The brown fox passed under the lazy dog.";
        String types[] = {"The quick brown (?<animal>.*) jumped over the lazy (?<target>.*).",
                "(?<animal>.*) became friends with (?<target>.*)"};
        Map<String, String> resultMap = StringUtils.extractVariablesFromString(input, Arrays.asList(types), "animal", "target1", "target");
        Assert.assertTrue(resultMap.isEmpty());
    }