使用正則表達式查找特定的簡單字符串

[英]Finding a specific, simple string with regexes


So I'm new to regular expressions and having difficulty understanding them. To get my feet wet, I've made one that identifies the date with either dashes or slashes. It looks like this:

所以我是正則表達式的新手,並且難以理解它們。為了弄濕我的腳,我做了一個用破折號或斜線標識日期。它看起來像這樣:

\d{1,2}[-/]\d{1,2}[-/](\d{4}|\d{2})

I realize it isn't 100% accurate because hypothetically it would accept 32-96-2012 as the date but that's fine. This isn't for homework or work so it doesn't need to be, I just want to understand simple regexes.

我意識到它不是100%准確,因為假設它會接受32-96-2012作為日期,但那沒關系。這不是為了家庭作業或工作,所以它不需要,我只想了解簡單的正則表達式。

So now I'd like to understand how to search for a specific word, and I'm quite confused. For example, if I wanted to search a text document for the word "soap", or "Tom". If anyone could post a simple example and description, I'd appreciate it!

所以現在我想了解如何搜索特定的單詞,我很困惑。例如,如果我想在文本文檔中搜索單詞“soap”或“Tom”。如果有人可以發布一個簡單的例子和​​描述,我會很感激!

2 个解决方案

#1


2  

a simple /soap/ or /Tom/ would do it.
more info http://www.codeproject.com/Articles/9099/The-30-Minute-Regex-Tutorial

一個簡單/肥皂/或/湯姆/會這樣做。更多信息http://www.codeproject.com/Articles/9099/The-30-Minute-Regex-Tutorial

#2


1  

Regular expressions are made to be as readable as possible (believe it or not). So if I wanted to search for a text document with the word soap, the regular expression is "soap".

正則表達式盡可能可讀(信不信由你)。因此,如果我想搜索帶有soap字樣的文本文檔,則正則表達式為“soap”。

If I wanted soap or Tom, then it becomes (?:soap|Tom). The (?:) enclosure means to treat the contents of the (?:) enclosure as its on mini regular expression. The | character is an or operator, meaning whatever's to the left or whatever to the right. So with that, (?:soap|Tom) means to find the word soap or the word Tom.

如果我想要肥皂或湯姆,那就變成了(?:肥皂|湯姆)。 (?:)機箱意味着將(?:)機箱的內容視為其迷你正則表達式。 | character是一個或一個運算符,意思是左邊的任何東西或者右邊的東西。因此,(?:soap | Tom)意味着找到肥皂這個詞或者湯姆這個詞。

Why couldn't I have written soap|Tom instead? If I wanted to look for "soap box" or "Tom box", then soap|Tom box would not work. This would match soap or Tom box, but not soap box.

為什么我不能寫肥皂|湯姆呢?如果我想找“肥皂盒”或“湯姆盒子”,那么肥皂|湯姆盒就行不通了。這將匹配肥皂或湯姆盒,但不匹配肥皂盒。

It's definitely confusing at first, but you learn to look for groupings and take it apart piece by piece to know what it's really looking for.

一開始它確實令人困惑,但你學會尋找分組並將它分開一塊一塊地知道它真正需要什么。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/04/06/7251f8ece38dd7597b1dfe8e25ef0a99.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com