使用带有正则表达式的 sscanf 输入 [英] Input using sscanf with regular expression

查看:44
本文介绍了使用带有正则表达式的 sscanf 输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想输入像

第一个(helloWorld):最后一个"

"First (helloWorld): last"

从那个字符串中,我想通过正则表达式只输入helloWorld".我正在使用

From that string I want to take input only "helloWorld" by regular expression. I am using

%*[^(] (%s):"

%*[^(] (%s):"

但这不符合我的目的.请有人帮我解决这个问题.

But that does not serve my purpose. Please somebody help me to solve this problem.

推荐答案

scanf 函数族中的格式说明符通常不被视为正则表达式的一种.

The format specifiers in the scanf family of functions are not generally considered to be a species of regular expression.

但是,你可以做你想做的事情.

However, you can do what you want something like this.

#include <stdio.h>

int main() {
  char str[256];
  scanf("First (helloWorld): last", "%*[^(](%[^)]%*[^\n]", str);
  printf("%s\n", str);
  return 0;
}

%*[^(]   read and discard everything up to opening paren
(        read and discard the opening paren
%[^)]    read and store up up to (but not including) the closing paren
%*[^\n]  read and discard up to (but not including) the newline

最后一个格式说明符在上述 sscanf 的上下文中不是必需的,但如果从流中读取并且您希望它位于当前行的末尾以供下一次读取时会很有用.不过请注意,换行符仍然留在流中.

The last format specifier is not necessary in the context of the above sscanf, but would be useful if reading from a stream and you want it positioned at the end of the current line for the next read. Note that the newline is still left in the stream, though.

与其使用 fscanf(或 scanf)直接从流中读取,不如使用 fgets 读取一行并且然后使用 sscanf

Rather than use fscanf (or scanf) to read from a stream directly, it's pretty much always better read a line with fgets and then extract the fields of interest with sscanf

// Read lines, extracting the first parenthesized substring.
#include <stdio.h>

int main() {
  char line[256], str[128];

  while (fgets(line, sizeof line, stdin)) {
    sscanf(line, "%*[^(](%127[^)]", str);
    printf("|%s|\n", str);
  }

  return 0;
}

样品运行:

one (two) three
|two|
four (five) six
|five|
seven eight (nine) ten
|nine|

这篇关于使用带有正则表达式的 sscanf 输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆