如何处理包含负号的字符串
我使用的是简单的正则[^0-9。]
,该与给定的字符串中的0到9和一个段之间的任何数字不匹配并与其余的匹配,我将其替换为空字符串然后,以字符串格式将我的有效值(整数或双)转换为整数或double。
例如:
'123A.478' => '123.478'
'123.48' => '123.48'
'123AX' => '123'
我也想处理负有价值的字符串,即,如果字符串具有“ -123”,我想保留它。因此,我需要将字符串转换为如下:
'--123.46' => '-123.46',
'123A-.46' => '123.46',
'-123--.46' => '-123.46',
'A-123-.46' => '-123.46'
我尝试使用量词,但我无法与现有的量发架构建正确的正则拨号。
有什么办法可以使用Regex实现这一目标?
I am using a simple regex [^0-9.]
that doesn't match any numbers between 0 to 9 and a period in my given string and matches the rest, and I replace that with empty string and then convert my valid value (integer or double) in string format into an integer or double.
For example:
'123A.478' => '123.478'
'123.48' => '123.48'
'123AX' => '123'
I want to also handle negative valued strings as well i.e. if a string has '-123', I want to retain it. So, I need to convert the strings as follows:
'--123.46' => '-123.46',
'123A-.46' => '123.46',
'-123--.46' => '-123.46',
'A-123-.46' => '-123.46'
I tried using a quantifier but I was unable to build a correct regex with my existing one.
Is there any way I can achieve this using regex?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能会使用交替删除示例字符串中的零件,然后在替换中使用一个空字符串。
说明
^
String的启动[^\ d \ s]+
匹配数字以外的1+ chars或Whitespace Char( ?= - )
断言-
直接在右|
或[^\ d \ s。]+
匹配1+除了数字,Whitespace char或dot(?!\ d)
以外的其他字符以外,直接向右边的数字声明a REGEX DEMO 和a php demo 。
示例代码
输出
You might use an alternation to remove the parts from the example strings, and in the replacement use an empty string.
Explanation
^
Start of string[^\d\s]+
Match 1+ chars other than a digit or a whitespace char(?=-)
Assert a-
directly to the right|
Or[^\d\s.]+
Match 1+ chars other than a digit, whitespace char or dot(?!\d)
Assert not a digit directly to the rightSee a regex demo and a PHP demo.
Example code
Output
您可以使用
php演示:
输出:
有两个步骤:
[^\ d .-]+
模式(除了数字,点或连字符以外的任何其他字符)均已从输入字符串,然后^( - )| - +
模式出现(字符串中的第一个字符将连字符放置在捕获组1中,所有其他连字符都刚刚匹配)$ 1
,第1组值(因此,所有连字符均被删除,但在字符串中是第一个)。You can use
See the PHP demo:
Output:
There are two steps:
[^\d.-]+
pattern (any char other than a digit, dot or hyphen) are removed from the input string and then^(-)|-+
pattern occurrences (the first char in the string that is a hyphen is placed into Capturing group 1 and all other hyphens are just matched) are replaced with$1
, Group 1 value (so, all hyphens are removed but the first one in the string).