捕获字符串中属性的值?

时间:2018-05-19 05:06:35

标签: java regex string

我在java中将文件内容作为String。我需要捕获属性代码的值,即key.test.textkey.test.text1

 <input type="button" value="<s:message code="key.test.text"  />"
 <input type="button2" value='<s:message code="key.test.text1'  />"

=之前可能有空格<input type="button" value = "<s:message code="key.test.text" />"

我不确定如何用正则表达式或字符串捕获它?

3 个答案:

答案 0 :(得分:-1)

您只需要对字符串进行json_encode,然后为您指定按钮值,然后您就可以阅读它了。

这是另一种解决方案。

首先使用StringEscapeUtils#unescapeHtml4()(或#unescapeXml(),具体取决于原始格式)到unescape。然后使用String#replaceAll()删除正在创建问题的字符。您可以从printable ASCII range获取帮助。

然后将其发送到按钮值。

答案 1 :(得分:-1)

使用正则表达式

import java.util.regex.Matcher;
import java.util.regex.Pattern;

String input = "...";
String regex = "value\\s*=\\s*[\"']<s:message\\s+code\\s*=\\s*[\"']([^\"']+)[\"']\\s*\\/>";

List<String> allMatches = new ArrayList<String>();
Matcher m = Pattern.compile(regex).matcher(input);

while (m.find()) {
  allMatches.add(m.group(1));
}

System.out.println(allMatches);

捕获组#1将为每个匹配返回所需的字符串。

Java代码:

static void Main(string[] args)
{
    Console.WriteLine("Hello World!");

    GPIO.PinMode(21, GPIO.Direction.Input, GPIO.Edge.Both);


    var fileSystemWatcher = new FileSystemWatcher();

    // Associate event handlers with the events
    fileSystemWatcher.Created += FileSystemWatcher_Created;
    fileSystemWatcher.Changed += FileSystemWatcher_Changed;
    fileSystemWatcher.Deleted += FileSystemWatcher_Deleted;
    fileSystemWatcher.Renamed += FileSystemWatcher_Renamed;

    // tell the watcher where to look
    fileSystemWatcher.Path = "/sys/devices/platform/soc/3f200000.gpio/gpiochip0/gpio/gpio21";

    // You must add this line - this allows events to fire.
    fileSystemWatcher.EnableRaisingEvents = true;


    Console.ReadLine();

}

private static void FileSystemWatcher_Renamed(object sender, RenamedEventArgs e)
{
    Console.WriteLine($"A new file has been renamed from {e.OldName} to {e.Name}");
}

private static void FileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)
{
    Console.WriteLine($"A new file has been deleted - {e.Name}");
}

private static void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
    Console.WriteLine($"A new file has been changed - {e.Name}");
}

private static void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)
{
    Console.WriteLine($"A new file has been created - {e.Name}");
}

测试此演示代码enter image description here

答案 2 :(得分:-1)

根据您的最新需求和以下评论接受的答案

    Matcher matcher = Pattern.compile(
            "<s:message.*?code.*?=.*?[\"'](.*?)[\"'].*?>")
            .matcher(content);

    int count = 0;
    while (matcher.find()) {
        System.out.println(matcher.group(1));

        ++count;
    }