简体   繁体   English

Shell脚本Linux,验证整数

[英]Shell script linux, validating integer

This code is for check if a character is a integer or not (i think). 此代码用于检查字符是否为整数(我认为)。 I'm trying to understand what this means, I mean... each part of that line, checking the GREP man pages, but it's really difficult for me. 我试图理解这是什么意思,我的意思是……该行的每一部分,都在检查GREP手册页,但这对我来说真的很困难。 I found it on the internet. 我在互联网上找到它。 If anyone could explain me the part of the grep... what means each thing put there: 如果有人能向我解释grep的一部分……那是什么意思呢?

echo $character | grep -Eq '^(\\+|-)?[0-9]+$'

Thanks people!!! 谢谢大家!!!

Analyse this regex: 分析此正则表达式:

'^(\+|-)?[0-9]+$'

^ - Line Start
(\+|-)? - Optional + or - sign at start
[0-9]+ - One or more digits
$ - Line End

Overall it matches strings like +123 or -98765 or just 9 总体来说,它匹配+123-98765或仅9类的字符串

Here -E is for extended regex support and -q is for quiet in grep command. -E用于扩展的正则表达式支持, -q用于grep命令中的安静模式。

PS: btw you don't need grep for this check and can do this directly in pure bash: PS:顺便说一句,您不需要grep进行此检查,可以直接在纯bash中执行此操作:

re='^(\+|-)?[0-9]+$'
[[ "$character" =~ $re ]] && echo "its an integer"

I like this cheat sheet for regex: 我喜欢正则表达式的备忘单:
http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/ http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

It is very useful, you could easily analyze the 这非常有用,您可以轻松分析

'^(+|-)?[0-9]+$' '^(+ | - )?[0-9] + $'

as

  • ^: Line must begin with... ^:行必须以...开头
  • (): grouping ():分组
  • \\: ESC character (because + means something ... see below) \\:ESC字符(因为+表示某些含义...参见下文)
  • +|-: plus OR minus signs + |-:加号或减号
  • ?: 0 or 1 repetation ?:0或1个重复
  • [0-9]: range of numbers from 0-9 [0-9]:数字范围从0-9
  • +: one or more repetation +:一个或多个重复
  • $: end of line (no more characters allowed) $:行尾(不允许更多字符)

so it accepts like: -312353243 or +1243 or 5678 因此它接受像-312353243或+1243或5678
but do not accept: 3 456 or 6.789 or 56$ (as dollar sign). 但不接受:3 456或6.789或56 $(以美元符号表示)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM