You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R语言中统计符合特定规则的@开头字符数量

Counting Valid @-Prefixed Substrings in a String

Hey there! Let's break down how to solve this problem step by step. First, let's restate the requirements clearly to make sure we're on the same page:

We need to count how many substrings in a given string meet these rules:

  • Starts with @
  • Only contains alphanumeric characters (letters/numbers), @, and underscores (_)
  • Total length is 10 characters or less

In your example string: vec <- " @_Jim98 Did you turn off the stove @9am?"

  • @_Jim98 is valid: it starts with @, only uses allowed characters, and is 7 characters long (well under 10)
  • @9am? is invalid: it includes a ? which isn't allowed, so it gets excluded
  • Final count should be 1

Solution Code (R)

Since your example uses R syntax, here's a practical implementation using regex and string manipulation:

# Example input string
vec <- " @_Jim98 Did you turn off the stove @9am?"

# Step 1: Extract all @-prefixed substrings (stop at spaces)
candidates <- stringr::str_extract_all(vec, "@[^\\s]+")[[1]]

# Step 2: Define regex pattern for valid substrings
# ^$ ensures we check the entire substring; allowed chars are @, letters, numbers, _; length 1-10
valid_pattern <- "^[@a-zA-Z0-9_]{1,10}$"

# Step 3: Filter candidates to keep only valid ones
valid_matches <- candidates[grepl(valid_pattern, candidates)]

# Step 4: Count the valid matches
count <- length(valid_matches)

# Output the result
cat("Total valid substrings:", count, "\n")

How This Works

  1. Extracting Candidates: str_extract_all(vec, "@[^\\s]+") grabs every substring that starts with @ and continues until the next space. For your example, this gives us ["@_Jim98", "@9am?"].
  2. Validity Check: The regex ^[@a-zA-Z0-9_]{1,10}$ makes sure:
    • The entire substring only uses allowed characters (no ?, !, etc.)
    • The total length is between 1 and 10 characters (since @ takes up one spot, we can have 0-9 more allowed characters)
  3. Counting: We use grepl to test each candidate against the pattern, then count how many pass.

When you run this code, it will output Total valid substrings: 1—exactly what we expect from your example.


内容的提问来源于stack exchange,提问作者user9605051

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:01:31