[英]forming correct regular expression in dynamic string
I have a FileInputStream who reads a file which somewhere contains a string subset looking like: 我有一个FileInputStream,它读取一个文件,该文件的某处包含一个字符串子集,如下所示:
...
OperatorSpecific(XXX)
{
Customer(someContent)
SaveImage()
{
...
I would like to identify the Customer(someContent)
part of the string and switch the someContent inside the parenthesis for something else. 我想识别字符串的
Customer(someContent)
部分,并将圆括号内的someContent切换为其他内容。
someContent will be a dynamic parameter and will contain a string of maybe 5-10 chars. someContent将是一个动态参数,将包含5-10个字符的字符串。
I have used regEx before, like once or twice, but I feel that in a context such as this where I don't know what value will be inside the parenthesis I'm at a loss of how I should express it... 我以前曾经使用过regEx,大概是一两次,但是我觉得在这样的背景下,我不知道括号内的值是什么,我不知道该如何表达...
In summary I want to have a string returned to me which has my someContent value inside the Customer-parenthesis. 总而言之,我想返回一个字符串,该字符串在Customer-括号内具有我的someContent值。
Does anyone have any bright ideas of how to get this done? 有人对如何完成这项工作有任何聪明的主意吗?
Try this one (double the escaping backslashes for the use in java!) 试试这个(将转义的反斜杠加倍,以便在Java中使用!)
(?<=Customer\()[^\)]*
And replace with your content. 并替换为您的内容。
See it here at Regexr 在Regexr上查看
(?<=Customer\\()
is look behind assertion. It checks at every position if there is a "Customer(" on the left, if yes it matches on the right all characters that are not a ")" with the [^\\)]*
, this is then the part that will be replaced. (?<=Customer\\()
在断言后面。它检查每个位置的左侧是否有“ Customer(”,如果是,则在右侧将所有非“)”字符与[^\\)]*
匹配[^\\)]*
,这就是将要替换的部分。
Some working java code 一些有效的Java代码
Pattern p = Pattern.compile("(?<=Customer\\()[^\\)]*");
String original = "Customer(someContent)";
String Replacement = "NewContent";
Matcher m = p.matcher(original);
String result = m.replaceAll(Replacement);
System.out.println(result);
This will print 这将打印
Customer(NewContent)
客户(新内容)
Untested, but something like the following should work: 未经测试,但类似以下内容的方法应该起作用:
Pattern pattern = Pattern.compile("\\s+Customer\\(\\s*(\\w+)\\s*\\)\\s*");
Matcher matcher = pattern.matcher(input);
matcher.matches();
System.out.println(matcher.group(1));
EDIT 编辑
This of course won't work with all possible cases: 当然,这不适用于所有可能的情况:
// legal variable names
Customer(_someContent)
Customer($some_Content)
Using groups works and non-greedy works: 使用小组作品和非贪婪作品:
String s =
"OperatorSpecific(XXX)\n {\n" +
" Customer(someContent)\n" +
" SaveImage() {";
Pattern p = Pattern.compile("Customer\\((.*?)\\)");
Matcher matcher = p.matcher(s);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
will print 将打印
someContent
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.