正则表达式用于查找正数和负数以及表达式。

huangapple go评论65阅读模式
英文:

Regex to find positive & negative numbers + expressions

问题

这是您的翻译内容:

我正在寻找正数和负数以及任何表达式在一个文本文件中的正则表达式这是我目前已经完成的代码

public class EquationsTextExtractor implements RegexTextExtractor{
@Override
public List<String> extract(String source) {
    List<String> equations = new ArrayList<>();
    Matcher matcher = Pattern.compile("\\d+(\\.\\d+)?\\s*[+\\-*/]\\s*\\d+(\\.\\d+)?").matcher(source);
    while (matcher.find()) {
        equations.add(matcher.group());
    }
    return equations;
}
}

当前的输出是

[02-495, 00-120, 2 + 2]
期望的输出是

2 + 2, -5.4 / -3.33

这是示例文本

这是一个示例源一个拥有PESEL号码12345678901的人来参加了一个拥有PESEL号码09876543211的课程这门课程在华沙02-495乌拉特·卢沃夫斯基街举行尽管最初他们想在00-120兹洛塔44举行但地方已经用完在课程中他们做了算术运算第一个例子是解决2 + 2但后来我们转向了负数它是-5.4 / -3.33变得有点困难
英文:

I'm looking for regex to find positive & negative numbers + any expressions in a text file. Here is what I've currenly done:

public class EquationsTextExtractor implements RegexTextExtractor{
@Override
public List&lt;String&gt; extract(String source) {
    List&lt;String&gt; equations = new ArrayList&lt;&gt;();
    Matcher matcher = Pattern.compile(&quot;\\d+(\\.\\d+)?\\s*[+\\-*/]\\s*\\d+(\\.\\d+)?&quot;).matcher(source);
    while (matcher.find()) {
        equations.add(matcher.group());
    }
    return equations;
}

}

The current output is:

[02-495, 00-120, 2 + 2]

The desired output is:

 2 + 2, -5.4 / -3.33

Here is sample text:

This is an example source in which a person with the PESEL number 12345678901 came to a course with a person with the PESEL number 09876543211. This course took place at the address Warszawa 02-495 Orląt Lwowskich street, although originally they wanted to do it at 00-120 Złota 44, but the place ended, at the course they did arithmetic operations, the first example was solving 2 + 2, but then we moved on to negative numbers and it was -5.4 / -3.33 and it got a little harder.

答案1

得分: 1

这个正则表达式将给你所期望的输出:
(?<![a-zA-Z])[+-]?(?:0|[1-9]\d*)(?:\.\d+)?\s+[*/+-]\s+[+-]?(?:0|[1-9]\d*)(?:\.\d+)?(?![a-zA-Z])
但是有一些情况未涵盖。

注意:为了获得这个正则表达式,我从你的正则表达式开始工作,然后进行了一些更改以获得所需的输出。

英文:

This regular expression will give you the desired output:

(?&lt;![a-zA-Z])[+-]?(?:0|[1-9]\d*)(?:\.\d+)?\s+[*/+-]\s+[+-]?(?:0|[1-9]\d*)(?:\.\d+)?(?![a-zA-Z])

but there will be some scenarios not covered

Note: to obtain this regular expression I started working with your regular expression and changing things to obtain the desired output

huangapple
  • 本文由 发表于 2023年1月8日 23:18:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048929.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定