regex - Bash Regex 如何检索值

标签 regex bash

我正在尝试使用正则表达式从以下文件内容中提取

# # Be sure to run `pod lib lint My Pod.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = "My Pod" s.version = "0.1.0" s.summary = "My Pod Stuff" # This description is used to generate tags and improve search results. # Think: What does it do? Why did you write it? What is the focus? # Try to keep it short, snappy and to the point. # Write the description between the DESC delimiters below. Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC Localize StoryBoard automatically. DESC s.homepage = "https://github.com/pod/MyPod.git" # s.screenshots = "www.example.com/screenshots_1", "www.example.com/screenshots_2" s.license = 'MIT' s.author = { } s.source = { :git => "https://github.com/controllerkit/MyPod.git", :tag => s.version.to_s } # s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>' s.platform = :ios, '7.0' s.requires_arc = true s.source_files = 'Pod/Classes/**/*' s.resource_bundles = { 'My Pod' => ['Pod/Assets/*.png'] } # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' s.dependency 'CocoaLumberjack', '~> 2' s.dependency 'BlocksKit' end

这是我正在使用的 bash,但 echo 没有返回任何内容。我的 bash 脚本中做错了什么?我基本上想从文件中提取 s.name 值,以便稍后在我的脚本中使用。

[[ "$podSpecValues" =~ 's\.name\s+=\s+"(.*?)"' ]] 
echo "${BASH_REMATCH[1]}"

其中 $podSpecValues 是上面文件的字符串。使用https://regex101.com/r/yZ3kM7/8显示正则表达式应该是正确的。

上面文件的输出应该是 My Pod

谢谢 DMC应用程序

最佳答案

尝试:

[[ "$podSpecValues" =~ s\.name\ +=\ +\"([^\"]*)\" ]] && echo "${BASH_REMATCH[1]}"

这就是我所看到的:

$ echo ${BASH_VERSION} 
4.3.11(1)-release
$ podSpecValues='Pod::Spec.new do |s| s.name = "My Pod" s.version = "0.1.0" s.summary = "It does stuff"'
$ [[ "$podSpecValues" =~ s\.name\ +=\ +\"([^\"]*)\" ]] && echo "${BASH_REMATCH[1]}" | cat -A
My Pod$

对OP的评论:

  • 从 Bash 3.2 开始,引用 RHS 模式会导致文字字符串匹配。我发现这非常违反直觉。

  • Bash 正则表达式风格将匹配空格 [[:space:]]不与 \s 。要匹配单个空格字符,请使用 "\ " (没有双引号!)。

  • 我不知道问号 ? 是什么?用于 () 内部.

  • ()内,*不得匹配双引号 " ,否则您将得到超出结束字符 " 的字符.

关于regex - Bash Regex 如何检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38780291/

相关文章:

regex - 使用正则表达式查找拼写错误

linux - Linux 中的 USB 插件/输出

macos - Bash .profile 未加载

bash - 如何根据双引号在 Bash 中的位置将其替换为两个不同的字符?

linux - 如何在 Bash 中终止 TCP 端口 16969?

javascript - 文本框中空白、制表符或空格的正则表达式

php - 基于输入的正则表达式创建

javascript - 正则表达式确保字符串以数字开头和结尾

regex - 如何使用两个正则表达式捕获组来创建两个 pandas 列

java - 使用-cp运行java程序