简体   繁体   中英

Regular Expression for matching a single digital followed by a word exactly in Notepad++

:Statement

Say we have following three records, and we just want to match the first one only -- exactly one digital followed by a specific word, what is the regular expression can be used to make it(in NotePad ++)?

  1. 2Cups
  2. 11Cups
  3. 222Cups

The expressions I tried and their problems are:

  • Proposal 1:\\d{1}Cups

it will find the "1Cups" and "2Cups" substrings in the second and third record respectively, which is what we do not want here

  • Proposal 2:[^0-9]+[0-9]Cups

same as the above

(PS: the records can be "XX 2Cups", "YY22Cups" and "XYZ 333Cups", ie, no assumption on the position of the matchable parts)

Any suggestions?

:Reference

[1] The reg definition in NotePad++ (Same as SciTe)

As mentioned in Searching for a complex Regular Expression to use with Notepad++ , it is: http://www.scintilla.org/SciTERegEx.html

[2] Matching exact number of digits

Here is an example: regular expression to match exactly 5 digits .

However, we do not want to find the match-able substring in longer records here.

If the string actually has the numbered sequence (1. 2Cups 2. 11Cups), you can use the white space that follows it:

\s\d{1}Cups

If there isn't the numbered list before, but the string will be at the beginning of the line, you can anchor it there:

^\d{1}Cups

Tested in Notepad++ v6.5.1 (Unicode).

It sounds like you want to match the digit only at the start of the string or if it has a space before it, so this would work:

(^|\b)\dCups

正则表达式可视化

Debuggex Demo

Explanation:

  • (^|\\b) Match the start of the string or beginning of a word (technically, word break)
  • \\d Match a digit ( {1} is redundant)
  • Cups Match Cups

This will work:

\b\dCups

If "Cups" must be a whole word (ie not matching 2Cupsizes :

\b\dCups\b

Note that \\b matches even if at start or end of input.

I found one possible solution:

  1. Using ^\\d{1}Cups to match "Starting with one digital + Cups" cases, as suggested by Ken, Cottrell and Bohemian.
  2. Using [^\\d]\\dCups to match other cases.

However, haven't found a solution using just one regex to solve the problem yet.

Have a try with:

(?:^|\D)\dCups

This will match xCups only if there aren't digit before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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